我有一张图像,我已读取它并将其转换为一个 numpy 数组。然后我将图像的每个颜色 channel (R、G、B)提取到三个单独的数组中:
import cv2
import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from itertools import cycle
from PIL import Image
image = Image.open('sample_images/fruit_half.png').convert('RGB')
image = np.array(image)
red = image[:,:,2]
green = image[:,:,1]
blue = image[:,:,0]
当我打印“红色”数组的值时,我得到以下输出:
print(red)
[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]]
我想知道red
、green
和blue
数组中的数字代表什么。它们是否代表特定像素的红/绿/蓝强度?任何见解都值得赞赏。
最佳答案
它们代表图像中每个颜色 channel 的像素强度。如果您打印出 image.shape
,您将能够访问它的属性
print(image.shape)
你会得到这样的东西
(93, 296, 3)
这告诉我们图像中的 (行、列、 channel )
。在这种情况下,图像具有三个 channel 。如果您打印出每个单独的 channel ,它们代表范围从 0-255
的像素强度。每个像素都由这三个 channel 的组合组成。相反,如果你打印出图像的形状,你会得到这个
(93, 296, 1)
表示图像只有一个 channel (灰度图)。
需要注意的一件事是 OpenCV 遵循 BGR
约定,而 PIL 遵循 RGB
。目前,你正在向后 split 。要使用 PIL 拆分 channel ,您可以这样做
image = Image.open('1.jpg').convert('RGB')
image = np.array(image)
red = image[:,:,0]
green = image[:,:,1]
blue = image[:,:,2]
请记住 PIL 使用 RGB
格式,其中红色在 channel 0 中,绿色在 channel 1 中,蓝色在 channel 2 中。
要使用 OpenCV 拆分 channel ,您可以这样做
image = cv2.imread('1.jpg')
b,g,r = cv2.split(image)
或
b = image[:,:,0]
g = image[:,:,1]
r = image[:,:,2]
以此图像为例,您可以使用直方图来可视化 channel 。
import cv2
from matplotlib import pyplot as plt
image = cv2.imread('1.jpg')
b,g,r = cv2.split(image)
blue = cv2.calcHist([b], [0], None, [256], [0,256])
green = cv2.calcHist([g], [0], None, [256], [0,256])
red = cv2.calcHist([r], [0], None, [256], [0,256])
plt.plot(blue, color='b')
plt.plot(green, color ='g')
plt.plot(red, color ='r')
plt.show()
关于python - NumPy:了解颜色矩阵中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56999223/