繁体   English   中英

如何使用python opencv找到图像中黑色物体的中心?

[英]How to find the center of black objects in an image with python opencv?

我在寻找白色背景上黑色物体的轮廓时遇到问题。

例子

在这里,我添加了一个图像示例。 现在我需要找到黑色区域的中心,并使用以下代码。

im = cv2.imread(img)
plt.imshow(im)
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(im, 60, 255, cv2.THRESH_BINARY_INV)
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

但是它给出了一个错误

TypeError: cv2.findeContours()的 image 参数的参数“image”的预期 Ptr

我该如何解决这个问题? 或者如果您有任何其他想法如何找到我想听的黑色区域的中心。 谢谢。

你在正确的轨道上。 当您在图像上执行查找轮廓时,OpenCV 预计要检测前景对象为白色,背景为黑色。 为此,您可以使用cv2.THRESH_BINARY_INV参数设置Otsu 阈值以获取白色对象。 从这里我们可以找到轮廓并通过使用cv2.moments计算质心来找到每个区域的中心 结果如下:

二进制图像

在此处输入图片说明

对象的中心以蓝色绘制,边界框为绿色。 您可以通过检查cXcY变量来获取每个轮廓的坐标。

在此处输入图片说明

您可以使用 Numpy 切片裁剪每个单独的 ROI,然后使用cv2.imwrite保存

在此处输入图片说明

代码

import cv2
import numpy as np

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread('1.png')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours
ROI_number = 0
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    # Obtain bounding rectangle to get measurements
    x,y,w,h = cv2.boundingRect(c)

    # Find centroid
    M = cv2.moments(c)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])

    # Crop and save ROI
    ROI = original[y:y+h, x:x+w]
    cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
    ROI_number += 1

    # Draw the contour and center of the shape on the image
    cv2.rectangle(image,(x,y),(x+w,y+h),(36,255,12), 4)
    cv2.circle(image, (cX, cY), 10, (320, 159, 22), -1) 

cv2.imwrite('image.png', image)
cv2.imwrite('thresh.png', thresh)
cv2.waitKey()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM