首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用cv2和Python进行图像中的对象检测

使用cv2和Python进行图像中的对象检测
EN

Stack Overflow用户
提问于 2021-01-14 18:38:50
回答 1查看 138关注 0票数 0

我有这样一张图片

我感兴趣的是找到这个图像中的对象(即点),并在每个对象周围画一个矩形。我开始了解cv2,并发现这可以很容易地完成。因此,到目前为止,我通过一些快速的google搜索写了以下代码:

代码语言:javascript
复制
import numpy as np
import matplotlib.pyplot as plt
import cv2 

print( cv2.__version__ )

# source data
img_file= "data1.png"

# create an OpenCV image
img= cv2.imread(img_file)

plt.imshow(img, cmap='gray')

# Define the classifiers

# pre-trained classifiers 
Point_classifier="haarcascade_eye.xml"   

# convert color image to grey image

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

# CREATE TRACKER

point_tracker=cv2.CascadeClassifier(Point_classifier)

# detect points
points= point_tracker.detectMultiScale(gray_img)
print(points)

Here I used `haarcascade_eye.xml` it looks similar to the point feature of the image, Is this correct? or do I need to use another classifier for this object?

但结果并不像预期的那样。我期待这样的数字,其中每个点都应该单独标记一个矩形形状。

关于这一点的任何帮助,或者我在代码中出错的地方。提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-01-14 21:35:57

haarcascade_eye.xml用于检测人眼。甚至还有不同的左眼和右眼。不要用那个。

您的代码行points= point_tracker.detectMultiScale(gray_img)正在失败,因为在您的图像中没有检测到眼睛。在这种情况下,您应该使用SimpleBlobDetector。在SimpleBlobDetector中,您可以根据需要过滤阈值、面积、圆度、凸度、惯性等。我试过了,但我的内核一直在死,可能是因为它的图像太大了。试一试小一点的。

但我们可以尝试其他方法-我找到了轮廓,然后根据面积对它们进行过滤,以避免出现小点。

代码语言:javascript
复制
import matplotlib.pyplot as plt
import cv2 

# source data
img_file= "data1.jpg"

# create an OpenCV image
img= cv2.imread(img_file)

# convert color image to grey image
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

im_gauss = cv2.GaussianBlur(gray_img, (5, 5), 0)
ret, thresh = cv2.threshold(im_gauss, 127, 255, 0)
# get contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

margin = 40
# calculate area and filter 
for con in contours:
    area = cv2.contourArea(con)
    if 100 < area < 500:
        x,y,w,h = cv2.boundingRect(con)
        cv2.rectangle(img, (x-margin, y-margin), (x + w+margin, y + h+margin), (0,255,0), 2)
        
plt.imshow(img, cmap='gray')

如果您想将3-4个点组合为一个点,您可以尝试:

1-当有重叠的边界框时,创建一个大的边界框。

2-闭合操作-在查找轮廓之前(膨胀后侵蚀)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65717419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档