如何使用OpenCV计数颜色检测对象

x8diyxa7  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(182)

我正在尝试使用颜色检测对象。下面是代码和图像:

import cv2
import numpy as np

img = cv2.imread('image2.jpeg')
img1 = img[157:498, 212:705]

hsv = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
lower_bound = np.array([0, 20, 20])
upper_bound = np.array([20, 255, 255])
origMask = cv2.inRange(hsv, lower_bound, upper_bound)
kernel = np.ones((7, 7), np.uint8)
mask = cv2.morphologyEx(origMask, cv2.MORPH_CLOSE, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

cv2.imshow("Mask", mask)
cv2.imshow("Crop Image", img1)
cv2.imshow("Orig Image", img)
    
cv2.waitKey(0)
cv2.destroyAllWindows()

所以在上面的代码中,我首先加载图像,然后将其裁剪到所需的区域,然后执行HSV来查找橙子对象。
下图为原图:

以下是裁剪后的图像:

以下是hsv后的蒙片图像:

我想知道怎样计算蒙版图像中物体的数量。例如,在这个例子中它是3。在计算完之后,我怎样在原始图像上的这些颜色物体上画边界框。

z8dt9xmd

z8dt9xmd1#

你可以使用你的二进制掩码来获得图像的轮廓。然后,你可以计算属于每个轮廓的边界矩形。假设输入是你的二进制掩码,脚本应该如下所示:

# imports:
import cv2

# image path
path = "D://opencvImages//"
fileName = "objectsMask.png" # This is your binary mask

# Reading an image in default mode:
inputImage = cv2.imread(path + fileName)

# Deep copy for results:
inputImageCopy = inputImage.copy()

# Convert RGB to grayscale:
grayscaleImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)

# Find the contours on the binary image:
contours, hierarchy = cv2.findContours(grayscaleImage, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Store bounding rectangles and object id here:
objectData = []

# ObjectCounter:
objectCounter = 1

# Look for the outer bounding boxes (no children):
for _, c in enumerate(contours):
    # Get the contour's bounding rectangle:
    boundRect = cv2.boundingRect(c)

    # Store in list:
    objectData.append((objectCounter, boundRect))

    # Get the dimensions of the bounding rect:
    rectX = boundRect[0]
    rectY = boundRect[1]
    rectWidth = boundRect[2]
    rectHeight = boundRect[3]

    # Draw bounding rect:
    color = (0, 0, 255)
    cv2.rectangle(inputImageCopy, (int(rectX), int(rectY)),
                  (int(rectX + rectWidth), int(rectY + rectHeight)), color, 2)

    # Draw object counter:
    font = cv2.FONT_HERSHEY_SIMPLEX
    fontScale = 1
    fontThickness = 2
    color = (0, 255, 0)
    cv2.putText(inputImageCopy, str(objectCounter), (int(rectX), int(rectY)), 
                font, fontScale, color, fontThickness)

    # Increment object counter
    objectCounter += 1

    cv2.imshow("Rectangles", inputImageCopy)
    cv2.waitKey(0)

我创建了一个名为objectData的列表,在这里,我存储了对象的“id”(只是一个对象计数器)和它的边界矩形,输出如下:

相关问题