【问题标题】:Detect circular objects with specific color检测具有特定颜色的圆形物体
【发布时间】:2018-10-01 13:01:36
【问题描述】:

我的目标是检测下图中的所有紫色花粉,并在其中输入字母“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 但还是不行。

【问题讨论】:

标签: python opencv


【解决方案1】:

如果你能仔细选择正确的hsv range,我认为你可以直接在HSV色彩空间中检测到紫色。此颜色图取自我的其他答案。

我为this task 选择Hue(120,160), Saturation(180, 255), Value(50, 255) 来获取掩码。

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (120, 180, 50), (160, 255, 255))

然后就可以对蒙版进行处理了。

链接可能有帮助:

  1. How to define a threshold value to detect only green colour objects in an image :Opencv

  2. Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

  3. RGB range for color red

【讨论】:

  • 这些值更适合紫色:H(126,145)、S(142, 255)、V(57, 255)。尝试使用此脚本轻松查找 HSV 范围:github.com/smeschke/juggling/blob/master/hsv_color_picker.py
  • HSV 使用起来有点困难,因为色调以红色包裹。如果您使用 HSV 没有获得好的结果,我建议您尝试 YUV 或 LAB,并为您想要在 UV(或 AB)平面中的紫色阴影创建一个边界框。
  • 谢谢。你能给我完整的代码吗?我不知道为什么,但我无法对面具进行圆圈检测,因为我的最后一个目的是将字母 P 写入花粉中。
  • 嘿,我的代码现在可以工作了,但我仍然不明白找到紫色范围的方法(我没有得到你附上的图片)。你能解释更多吗?
猜你喜欢
  • 2011-03-09
  • 1970-01-01
  • 2013-01-28
  • 1970-01-01
  • 2022-01-18
  • 2016-08-29
  • 2012-04-04
  • 2011-06-30
  • 1970-01-01
相关资源
最近更新 更多