我想提取一些形状并根据该图像中的形状颜色创建蒙版
(应为红色形状创建蒙版)并低于预期数字 然后我想确定这些形状的面积。
import cv2
import numpy as np
from matplotlib import pyplot as plt
from colorthief import ColorThief
ct=ColorThief('image_red.png')
domainant_color = ct.get_color(quality=1)
palette = ct.get_palette(color_count=number_colors)
print(palette)
plt.imshow([[palette[i] for i in range(number_colors)]])
plt.show()
#LOAD IMAGE
image_org=cv2.imread("image_red.png",0)
print(image_org.shape)
#FILTER /REMOVE NOISES
img_filter=cv2.medianBlur(image_org, 3)
#### THRESHOLDING..
thresh_value,thresh_img=cv2.threshold(img_filter,0,225,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
low=np.array([251, 4, 4], dtype = "uint8") #this is based on values from palette
upper=np.array([251, 4, 4], dtype = "uint8")#this is based on values from palette
img_f = cv2.cvtColor(thresh_img, cv2.COLOR_BGR2RGB)
mask1=cv2.inRange(img_f,lo,up)
io.imshow(mask1)
plt.show()
我通过以下步骤开始:
结果似乎给了我其他阶段,而不是红色形状。我该怎么做才能只获得我附加的预期图像文件中的红色形状?
除非您的问题具有误导性,否则您只是在寻找彩色像素。通过转换为 HSV 色彩空间 并寻找高饱和度的像素,最容易找到这些,因为黑色、白色和灰色像素的饱和度都为零。
代码将如下所示:
#!/usr/bin/env python3
import numpy as np
import cv2 as cv
# Load image and convert to HSV colourspace
im = cv.imread('YOURIMAGE.jpg')
HSV = cv.cvtColor(im,cv.COLOR_BGR2HSV)
# Select the Saturation channel
S = HSV[:,:,1]
# Save Saturation channel for debug purposes
cv.imwrite('DEBUG-sat.png', S)
# Decide some threshold
# Save thresholded Saturation channel for debug purposes
thr = S>50
cv.imwrite('DEBUG_thr.png', thr*255)
# Count the saturated pixels and total image area
Nsat = np.count_nonzero(thr)
area = im.shape[0]*im.shape[1]
# Output results
print(f'{Nsat=}, {area=}')
打印:
Nsat=6774, area=436230
中间的调试图像如下所示: