python - 检测白色背景图像中的轮廓

标签 python image opencv

我无法检测这张图片中的轮廓

类图图片

我想检测图中的所有边界轮廓,但到目前为止我的程序只检测图像中显示的图像边界

忽略中间的0,表示是轮廓0。

我不确定问题出在我的代码中,因为它可以检测黑色背景图像中的轮廓。

filename = sys.argv[1]
t = int(sys.argv[2])
img = cv2.imread(filename)

resized = imutils.resize(img, width=300)
ratio = img.shape[0] / float(resized.shape[0])

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
(t, binary) = cv2.threshold(blur, t, 255, cv2.THRESH_BINARY)

_ ,cnts, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

for (i,c) in enumerate(cnts):
    M = cv2.moments(c)
    if M["m00"] != 0:
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
    else:
        cX, cY = 0, 0
    (x,y,w,h) = cv2.boundingRect(c)
    area = cv2.contourArea(c)
    cv2.rectangle(img, (x, y), (x + w, y + h),(0, 255, 255), 2)
    print("Object %d has dimensions x=%d, y=%d, w=%d, h=%d area=%d" % (i,x,y,w,h,int(w*h)))
    cv2.putText(img, str(i), (cX, cY),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)

最佳答案

I am note sure where the problem lies in my code as it can detect contours in images with a black background.

这几乎肯定是您的问题。来自OpenCV tutorial

In OpenCV, finding contours is like finding white object from black background. So remember, object to be found should be white and background should be black.

This SO Q/A向您展示如何反转图像。

正如所讨论的那样,您肯定需要检测黑底白字 here

关于python - 检测白色背景图像中的轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49924470/

相关文章:

python - 如何在 numpy 数组中加载多个图像?

python - 导入错误 : No module named cv2 in ubuntu 16. 04 Anaconda2

python - 尝试在 Mac OS X 上设置 Enthought enpkg 时出现钥匙串(keychain)问题

python - 在Django中,如何将上传的pdf文件转换为图像文件并保存到数据库中的相应列?

javascript - 完成页面加载后执行功能

Javascript 监听图像加载调用并在图像加载之前更改 src

python - 将 h264 字节字符串转换为 OpenCV 图像

python - 是否可以在 IPython/JuPyter Notebook 中显示 OpenCV 视频?

python - 区分 False 和 0

python - Python 中未初始化的值?