我想做的本质上是删除 3D numpy 数组中的所有行
h,s
a
如果 a[h,s,v] = some value
对于所有 v
更具体地说,我从
cv2
加载了一个图像,其中包含一些透明像素。我想创建一个不包含透明像素的 HSV 直方图(即 k=255
)
这是我现在拥有的:
import cv2
import numpy as np
IMAGE_FILE = './images/2024-11-17/00.png' # load image with some transparent pixels
# Read image into HSV
image = cv2.imread(IMAGE_FILE)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Remove all pixels with V = 255
hsv_removed_transparency = []
i = np.where(hsv[:, :, 2] == 255) # indices of pixels with V = 255
for i1 in range(len(i[0])):
hsv_removed_transparency.append(np.delete(hsv[i[0][i1]], i[1][i1], axis=0)
如果您想使用掩模计算直方图,就这样做吧。无需更改图像。
cv2.calcHist
采用 mask
参数:
import cv2
image = cv2.imread('squirrel_cls.jpg')
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# add some more values with V = 255
hsv[100:350, 150:350, 2] = 255
h_hist_all = cv2.calcHist([hsv], [0], None, [256], [0, 256])
s_hist_all = cv2.calcHist([hsv], [0], None, [256], [0, 256])
mask = (hsv[..., 2] != 255).astype(np.uint8)
h_hist = cv2.calcHist([hsv], [0], mask, [256], [0, 256])
s_hist = cv2.calcHist([hsv], [0], mask, [256], [0, 256])
import matplotlib.pyplot as plt
plt.plot(h_hist_all, label='H (all)')
plt.plot(h_hist, label='H (mask)')
plt.legend()
输出: