Mahotas 简明教程

Mahotas - Creating RGB Image

RGB 图像是一种使用红、绿和蓝颜色模型来表示颜色的数字图像。RGB 图像中的每个像素由三个颜色通道表示:红色、绿色和蓝色,它们存储每个颜色的强度值(范围从 0 到 255)。

例如,三个通道(255, 255, 255)中的全部强度代表白色,而三个通道(0, 0, 0)中的零强度代表黑色。

Creating RGB Images in Mahotas

Mahotas 中的 RGB 图像是形状为(h、w、3)的三维数组;其中 h 和 w 是图像的高度和宽度,3 表示三个通道:红色、绿色和蓝色。

要使用 Mahotas 创建 RGB 图像,您需要定义图像的尺寸,使用所需尺寸创建一个空 Numpy 数组,并设置每个通道的像素值。

Example

以下是一个在 mahotas 中从红色到绿色水平渐变和从蓝色到白色垂直渐变的示例:

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

Creating an RGB Image from Color Intensities

颜色强度是指表示图像中每个颜色通道的强度或大小的值。高强度值会导致更鲜艳或更饱和的颜色,而低强度值会导致更暗或较不饱和的颜色。

要使用 Mahotas 根据颜色强度创建 RGB 图像,您需要创建表示红色、绿色和蓝色颜色通道强度的单独数组。这些数组应具有与所需输出图像相同的尺寸。

Example

在以下示例中,我们正在从随机生成的颜色强度创建一个随机 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

Creating an RGB Image from a Single Color

要从单一颜色创建 RGB 图像,您可以使用所需的尺寸初始化一个数组,并为每个像素分配相同的 RGB 值。这导致整个图像中统一的色彩外观。

Example

在这里,我们通过使用 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