如何使用 OpenCV 计算检测到的颜色对象

发布于 2025-01-14 12:53:06 字数 1203 浏览 0 评论 0原文

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

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。计数后,如何在原始图像上的这些颜色对象上绘制边界框。

I am trying to detect objects using color. Below is the code and the image:

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()

So in the above code, I am loading the image first. Then cropping it to a desired area and then performing the HSV to find orange color objects.

Below is the original image:

enter image description here

Below is the cropped image:

enter image description here

Below is the mask image after hsv:

enter image description here

I want to know how can I count the number of objects in the mask image. For example, in this case it is 3. And after counting it, how can I draw bounding box over these color objects on the original image.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

飘然心甜 2025-01-21 12:53:06

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

# 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”(只是一个对象计数器)及其边界矩形。这是输出:

在此处输入图像描述

You can use your binary mask to get the contours of the image. Then, you can compute the bounding rectangles belonging to each contour. Assume the input is your binary mask, the script should look like this:

# 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)

I'm creating a list called objectData. Here, I'm storing the object's "id" (just an object counter) and its bounding rectangle. This is the output:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文