python - NumPy:了解颜色矩阵中的值

标签 python numpy opencv computer-vision

我有一张图像,我已读取它并将其转换为一个 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]]

我想知道redgreenblue 数组中的数字代表什么。它们是否代表特定像素的红/绿/蓝强度?任何见解都值得赞赏。

最佳答案

它们代表图像中每个颜色 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 。

enter image description here enter image description here

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/

相关文章:

python - matplotlib中2个y坐标之间的阴影区域

python - 使用numpy读取和操作Fortran有序数组的最佳实践

c++ - 使用 `libopencv_ffmpeg.so` 在 Linux 上构建 OpenCV 2.4.11

c++ - CV_RETR_LIST、CV_RETR_TREE、CV_RETR_EXTERNAL 之间的区别?

python - 如何获取满足特定条件的行的索引号

python - 用 pandas 解析 CSV 并转换为 dict 结果仅在最后一行出现 KeyError

python - 在 df 列中指定可变窗口大小的 Pandas rolling_max

python - 将大量数据存储到 numpy 数组中

pandas - 有条件地用其他行值填充空行值

macos - opencv 可以与 Objective C 混合编译以进行 OS X 应用程序开发吗?