【发布时间】:2022-01-02 06:51:27
【问题描述】:
我正在使用 opencv 处理图像,我的部分问题要求我通过图像的颜色迭代图像,并且只显示与某些颜色范围匹配的颜色。如何找到最大和最小 bgr 值?
【问题讨论】:
-
我认为这是重复的。答案是
cv.inRange的问题很多。
我正在使用 opencv 处理图像,我的部分问题要求我通过图像的颜色迭代图像,并且只显示与某些颜色范围匹配的颜色。如何找到最大和最小 bgr 值?
【问题讨论】:
cv.inRange 的问题很多。
这是一种在 Python/OpenCV 中执行此操作的方法。
我们基本上找到红色掩蔽后R,G,B通道的平均值最小的颜色和红色掩蔽后R,G,B通道的平均值最大的颜色。
- Read the input
- Select color -- in this case red
- Threshold the image for the color as a mask
- Separate channels
- Get the average image of the 3 channels
- Find the min and max values in the average image
- Create a mask for the min values
- Create a mask for the max values
- Combine the original mask with the min mask
- combine the original mask with the max mask
- Get the coordinates for all pixels where the combined mask and min mask is white.
- Find the color corresponding to the first coordinate found if more than one
- Get the coordinates for all pixels where the combined mask and max mask is white.
- Find the color corresponding to the first coordinate found if more than one
输入:
import cv2
import numpy as np
# load image
img = cv2.imread('mandril3.jpg')
# create mask for red
lower=np.array((20,40,215))
upper=np.array((100,120,255))
mask = cv2.inRange(img, lower, upper)
# mask the image for viewing
result = img.copy()
result[mask!=255] = (0,0,0)
# separate channels
b,g,r = cv2.split(img)
# get average of channels
ave = cv2.add(b,g,r)/3
ave = ave.astype(np.uint8)
# get min and max for ave
ave_min = np.amin(ave[np.where(mask==255)])
ave_max = np.amax(ave[np.where(mask==255)])
# form min and max masks from ave
mask_min = ave.copy()
mask_min[ave==ave_min] = 255
mask_min[ave!=ave_min] = 0
mask_max = ave.copy()
mask_max[ave==ave_max] = 255
mask_max[ave!=ave_max] = 0
# combine min mask with red mask
red_mask_min = cv2.bitwise_and(mask, mask_min)
# combine max mask with red mask
red_mask_max = cv2.bitwise_and(mask, mask_max)
# get coordinates where masks are white and corresponding color - take first one
min_list = np.argwhere(red_mask_min==255)
min_count = len(min_list)
if min_count != 0:
min_coord = min_list[0]
y=min_coord[0]
x=min_coord[1]
min_color = img[y:y+1, x:x+1][0][0]
print("min_red:", min_color)
max_list = np.argwhere(red_mask_max==255)
max_count = len(max_list)
if max_count != 0:
max_coord = max_list[0]
y=max_coord[0]
x=max_coord[1]
max_color = img[y:y+1, x:x+1][0][0]
print("max_red:", max_color)
# save results
cv2.imwrite("mandril3_nose_mask.jpg", mask)
cv2.imwrite("mandril3_nose.jpg", result)
# show images
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.imshow("ave", ave)
cv2.imshow("red_mask_min", red_mask_min)
cv2.imshow("red_mask_max", red_mask_max)
cv2.waitKey(0)
cv2.destroyAllWindows()
红色面具:
蒙面图像:
结果:
min_red: [ 22 57 244]
max_red: [ 99 120 242]
【讨论】: