Mahotas - 建立RGB影像



RGB影像是一種數字影像,它使用紅、綠、藍顏色模型來表示顏色。RGB影像中的每個畫素都由三個顏色通道表示——紅色、綠色和藍色,它們儲存每個顏色的強度值(範圍從0到255)。

例如,所有三個通道都具有全強度(255、255、255)的畫素表示白色,而所有三個通道都具有零強度(0、0、0)的畫素表示黑色。

在Mahotas中建立RGB影像

在Mahotas中,RGB影像是一個形狀為(h,w,3)的三維陣列;其中h和w分別是影像的高度和寬度,3表示三個通道:紅色、綠色和藍色。

要使用Mahotas建立RGB影像,您需要定義影像的尺寸,建立一個具有所需尺寸的空NumPy陣列,並設定每個通道的畫素值。

Mahotas沒有直接建立RGB影像的函式。但是,您可以使用NumPy和Mahotas庫來建立RGB影像。

示例

以下是如何在Mahotas中建立從紅色到綠色水平漸變、從藍色到白色垂直漸變的RGB影像的示例:

import mahotas as mh
import numpy as np
from pylab import imshow, show
# Define the dimensions of the image
width = 200
height = 150
# Create an empty numpy array with the desired dimensions
image = np.zeros((height, width, 3), dtype=np.uint8)
# Set the pixel values for each channel
# Here, we'll create a gradient from red to green horizontally and blue to
white vertically
for y in range(height):
   for x in range(width):
      # Red channel gradient
      r = int(255 * x / width)
      # Green channel gradient
      g = int(255 * (width - x) / width)
      # Blue channel gradient
      b = int(255 * y / height)
      # Set pixel values
      image[y, x] = [r, g, b]
# Save the image
mh.imsave('rgb_image.png', image)
# Display the image
imshow(image)
show()

輸出

以下是上述程式碼的輸出:

Creating RGB Image

從顏色強度建立RGB影像

顏色強度是指表示影像中每個顏色通道的強度或幅度的值。較高的強度值會導致更亮或更飽和的顏色,而較低的強度值會導致更暗或更不飽和的顏色。

要使用Mahotas從顏色強度建立RGB影像,您需要建立單獨的陣列來表示紅色、綠色和藍色顏色通道的強度。這些陣列應該與所需的輸出影像具有相同的尺寸。

示例

在下面的示例中,我們從隨機生成的色彩強度建立了一個隨機的RGB噪聲影像:

import mahotas as mh
import numpy as np
from pylab import imshow, show
# Create arrays for red, green, and blue color intensities
red_intensity = np.random.randint(0, 256, size=(100, 100), dtype=np.uint8)
green_intensity = np.random.randint(0, 256, size=(100, 100), dtype=np.uint8)
blue_intensity = np.random.randint(0, 256, size=(100, 100), dtype=np.uint8)
# Stack color intensities to create an RGB image
rgb_image = np.dstack((red_intensity, green_intensity, blue_intensity))
# Display the RGB image
imshow(rgb_image)
show()

輸出

執行上述程式碼後,我們將得到以下輸出:

Image Color Intensities

從單一顏色建立RGB影像

要從單一顏色建立RGB影像,您可以使用所需尺寸初始化一個數組,並將相同的RGB值分配給每個畫素。這會導致整個影像呈現統一的顏色外觀。

示例

在這裡,我們透過將顏色設定為藍色(使用RGB值(0, 0, 255))來建立單色影像:

import mahotas as mh
import numpy as np
from pylab import imshow, show
# Define the dimensions of the image
width, height = 100, 100
# Create a single color image (blue in this case)
blue_image = np.full((height, width, 3), (0, 0, 255), dtype=np.uint8)
# Display the blue image
imshow(blue_image)
show()

輸出

獲得的影像如下:

Image Single Color
廣告