Python 检测具有特定颜色的圆形对象
我的目标是检测下图中的所有紫色花粉,并在其中添加字母“p”。 但结果表明,它总是错误的黑色区域 更改圆检测中的半径不会有帮助,因为我还有很多类似的图像要处理。那我该怎么做才能更好呢 这是我的密码:Python 检测具有特定颜色的圆形对象,python,opencv,Python,Opencv,我的目标是检测下图中的所有紫色花粉,并在其中添加字母“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
# 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)
此外,我还尝试使用颜色检测,因为我想要检测的所有颜色都是相同的(紫色)。我遵循
但是它仍然不起作用。如果你能仔细选择正确的
HSV范围,我认为你可以直接在HSV颜色空间中检测紫色。这个颜色图是从我的其他答案中提取的
我为此任务选择色调(120160)、饱和度(180255)、值(50255)
,以获得遮罩
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (120, 180, 50), (160, 255, 255))
然后,您可以在遮罩上进行处理
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (120, 180, 50), (160, 255, 255))
链接可能有帮助:
将问题分为两部分:(a)过滤颜色(使其他颜色为黑色)和(b)检测圆。类似于此问题?这些值更适合紫色:H(126145)、S(142255)、V(57255)。尝试使用此脚本轻松找到HSV范围:HSV有点难以使用,因为色调包裹在红色处。如果你在HSV上没有得到很好的效果,我建议你试试YUV或LAB,并在UV(或AB)平面上为你想要的紫色阴影创建一个边界框。谢谢。你能给我完整的密码吗?我不知道为什么,但我无法对面具进行圆圈检测,因为我的最后一个目的是在花粉中写入字母P。嘿,我的代码现在工作了,但我仍然不知道如何找到紫色的范围(我没有你附上的图片)。你能再解释一下吗?