我的目标是检测下图中的所有紫色花粉,并将字母“ P”放入其中。
但是结果表明,它总是会误认为黑色区域。
在圆检测中更改半径无济于事,因为我还有很多相似的图像要去。那我该怎么做才能改善它?
这是我的代码:
# coding: utf-8
import cv2
import numpy as np
path = "./sample.JPG"
font = cv2.FONT_HERSHEY_COMPLEX
def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
# initialize the dimensions of the image to be resized and
# grab the image size
dim = None
(h, w) = image.shape[:2]
# if both the width and height are None, then return the
# original image
if width is None and height is None:
return image
# check to see if the width is None
if width is None:
# calculate the ratio of the height and construct the
# dimensions
r = height / float(h)
dim = (int(w * r), height)
# otherwise, the height is None
else:
# calculate the ratio of the width and construct the
# dimensions
r = width / float(w)
dim = (width, int(h * r))
# resize the image
resized = cv2.resize(image, dim, interpolation = inter)
# return the resized image
return resized
iml = cv2.imread(path,cv2.IMREAD_COLOR)
img = image_resize(iml,width=960)
cimg = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
#cv2.GaussianBlur(cimg, (9,9),3)
cimg = cv2.medianBlur(cimg,5)
circles = cv2.HoughCircles(cimg[:,:,0],cv2.HOUGH_GRADIENT,1,cimg.shape[0]/16,param1=15,param2=20,minRadius=18,maxRadius=38)
circles = np.uint16(np.around(circles))[0,:]
for i in circles:
cv2.putText(img,'P',(i[0],i[1]), font, 0.5,(0,255,0),1,cv2.LINE_AA)
cv2.imwrite("./output.jpg",img)
此外,我还尝试使用颜色检测,因为我要检测的所有颜色都具有相同的颜色(紫色)。我遵循instructions here 但仍然没有用。
答案 0 :(得分:3)
我认为,如果您可以谨慎选择正确的hsv range
,则可以直接在HSV颜色空间中检测到紫色。此颜色图来自我的其他答案。
我为Hue(120,160), Saturation(180, 255), Value(50, 255)
选择this task
以获取掩码。
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (120, 180, 50), (160, 255, 255))
然后您可以在面罩上进行处理。
链接可能会有所帮助: