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

标签 python image opencv image-processing computer-vision

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

example

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

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: Expected Ptr for argument 'image' " for the image argument of cv2.findeContours().



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

最佳答案

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

二进制图像

enter image description here

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

enter image description here

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

enter image description here

代码

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

关于python - 如何使用python opencv找到图像中黑色物体的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60486029/

相关文章:

java - android 用相机拍摄多张图像

python - Pandas:基于列 Dtype 的通用数据插补

python - Jinja 按字母顺序对大小写混合的列表进行排序

python - 解析反斜杠分隔的层次结构路径(不同的级别数)

python - TensorFlow 中的高效图像膨胀

c++ - openCV 将 IplImage 与 cv::Mat 混合

matlab - 如何更改二维图像的视口(viewport)?

python - 分别分割每个轮廓

python - 线程中的线程

ajax - Drupal 7 - 图像字段上传/删除不起作用