OpenCV颜色检测,不需要先验颜色

时间:2018-02-20 23:32:32

标签: python image opencv image-processing

我想在一些颜色斑点周围绘制边界框,颜色我事先不知道。图像看起来像这样: enter image description here

场景中的每种颜色代表不同的对象。我已经在图像的灰度版本上尝试了findContours,但是如果它们重叠,那么获得的轮廓包含多个对象。我希望获得单个对象的轮廓,或者如果对象被场景中的另一个对象分割,则获得对象的多个轮廓。有没有办法在OpenCV中实现这一目标? 非常感谢您的关注和时间!

编辑:按照建议,这里是我的代码

img = cv2.imread(img_path)

imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

kernel = np.ones((5,5), np.uint8)

im2, contours, hierarchy = cv2.findContours(imgray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

bboxes = []

for c in contours:
    x, y, w, h = cv2.boundingRect(c)
    M = cv2.moments(c)
    if M["m00"]:
        cx = int(M['m10']/M['m00'])
        cy = int(M['m01']/M['m00'])
        area = cv2.contourArea(c)
        if area >= 25:
            colorHash = img[cy, cx]
            bboxes.append((Box(Point(x, y), Point(x+w, y+h)), colorHash, area))
            cv2.drawContours(img, [c], -1, (0, 0, 255), 1)

cv2.imshow("Image", img)
cv2.waitKey(0)   

return bboxes, contours

这里是我正在尝试解决的问题的图像(标记为蓝色,轮廓为红色,对象应具有单独的轮廓)

enter image description here

3 个答案:

答案 0 :(得分:0)

您可以对图像的HSV颜色空间进行光栅扫描,并根据某些色调范围的色调值对每个像素进行分类。 之后,使用不同的色调值类对图像进行遮罩,从而对不同颜色的每个单独对象进行分割。

答案 1 :(得分:0)

  1. 请发布您的代码,以便我们可以查看错误的位置或为您的方法提供更好的建议。
  2. 以下代码绘制图像中单个对象的轮廓:
  3. `

    # -i : image path
    
    # import stuff
    import numpy as np
    import argparse
    import cv2
    
    # Construct argument 
    ap = argparse.ArgumentParser()
    ap.add_argument( "-i", "--image", required = True, help = "Path to the image")
    ap.add_argument("-t", "--threshold", type = int, default = 100, help = "Enter threshold value")
    args = vars(ap.parse_args())
    
    # load image / grayscale
    image = cv2.imread(args["image"])
    print (image.shape)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    kernel = np.ones((5,5), np.uint8)
    # blur the image for a mask
    img = cv2.erode(gray, kernel, iterations=1)
    img = cv2.dilate(img, kernel, iterations=1)
    blurred = cv2.blur(img, (3,3))
    
    # Threshold image to segment the objects
    # requires grayscale image
    methods = [
        ("THRESH_BINARY", cv2.THRESH_BINARY)
        #("THRESH_BINARY_INV", cv2.THRESH_BINARY_INV)
        ]
    
    # loop for each threshold method
    # (T, threshImage) = cv2.threshold(src, thresh, maxval, type)
    for (threshName, threshMethod) in methods:
        (T, threshImage) = cv2.threshold(blurred, args["threshold"], 255, threshMethod)
        cv2.namedWindow(threshName,cv2.WINDOW_NORMAL)
        cv2.resizeWindow(threshName, 600,600)
        cv2.imshow(threshName, threshImage)
        cv2.waitKey(0)
    
    # # Adaptive thresholding
    # adaptiveThresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 4)
    
    # Crop target image using thresh as mask
    masked = cv2.bitwise_and(gray, gray, mask = threshImage)
    # cv2.imshow("Mased Image", masked)
    # cv2.waitKey(0)
    
    # find contours
    (_, cnts, _) = cv2.findContours(masked.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    print (" No. of Contours ={}".format(len(cnts)))
    
    # draw the contours on top of the original image
    drops = image.copy()
    cv2.drawContours(drops, cnts, -1, (0, 255, 0), 2)
    cv2.namedWindow("Contours",cv2.WINDOW_NORMAL)
    cv2.resizeWindow("Contours", 600,600)
    cv2.imshow("Contours", drops)
    cv2.waitKey(0)
    
    cv2.imwrite('contours.png',drops)
    

答案 2 :(得分:0)

两种方法:

  • 使用轮廓方法,并保持斑点的颜色(轮廓中的任何像素)以及边界框。然后合并相同颜色的边界框。这可以通过颜色索引的边界框字典来帮助完成。

  • 扫描图像,从空字典开始。每次遇到非黑色像素时,查找其颜色并创建或更新边界框。

请注意,无需转换为其他颜色系统,请保留原始RGB。