繁体   English   中英

如何检测图像中是否存在次要对象

[英]How Can I Detect If There are Secondary Objects in an Image

我正在寻找一种方法来检测图像中是否有辅助对象,或者图像是否只有一个主要的 object。 我做了一些研究,但我找不到任何与我正在寻找的东西完全一样的东西。

一个示例图像是:

主要的 object 是两个洗涤剂瓶,因为它们重叠,而辅助 object 将是右上角的“2 包”弹出气泡。 我希望这张图片返回类似:“这张图片有次要对象”或对象的数量。

这是在 Python/OpenCV 中执行此操作的一种方法

  • 读取输入
  • 转换为灰色并反转
  • OTSU 阈值
  • 形态关闭
  • 获取外部轮廓
  • 在图像上绘制轮廓
  • 计算轮廓
  • 打印信息
  • 保存结果

输入:

在此处输入图像描述

import cv2
import numpy as np

# read image
img = cv2.imread("tide.jpg")

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# invert gray image
gray = 255 - gray

# threshold gray image
#thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

# apply morphology close
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# Get contours
cntrs = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
result = img.copy()
for c in cntrs:
    cv2.drawContours(result, [c], -1, (0,0,255), 1)

count = len(cntrs)
print("")
print("count =",count)

print("")

if count > 1:
    print("This image has secondary objects")
else:
    print("This image has primary object only")

# write results to disk
cv2.imwrite("tide_thresh.png", thresh)
cv2.imwrite("tide_morph.png", morph)
cv2.imwrite("tide_object_contours.png", result)

# display it
cv2.imshow("thresh", thresh)
cv2.imshow("morph", morph)
cv2.imshow("result", result)
cv2.waitKey(0)


阈值图像:

在此处输入图像描述

形态关闭图像:

在此处输入图像描述

图像轮廓:

在此处输入图像描述

轮廓和消息的计数:

count = 2

This image has secondary objects


按照@fmw42 的建议,我做了一些研究,发现一个脚本经过一些修改后运行良好:

import cv2
import numpy as np
import sys


img = cv2.imread(sys.argv[1], cv2.IMREAD_UNCHANGED)

#convert img to grey
img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#set a thresh
thresh = 230
#get threshold image
ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY_INV)
#find contours
contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

#create an empty image for contours
# img_contours = np.zeros(img.shape)
img_contours = np.zeros_like(img)
# draw the contours on the empty image
cv2.drawContours(img_contours, contours, -1, 255, 3)
#save image
cv2.imshow('contours',img_contours)
# Wait indefinitely until you push a key.  Once you do, close the windows

print len(contours)

cv2.waitKey(0)
cv2.destroyAllWindows()

我的主要问题是阈值设置,我发现 230 最适合我的示例图像,尽管它仍然不完美。 我希望有更好的方法或我可以添加的东西。

此图像按预期返回 1,但我的初始测试图像在此阈值设置下返回 3,而我预期为 2。在 200 thresh 时它返回 2,但我愿意妥协,因为我需要知道的主要事情是它是否更多大于 1。

暂无
暂无

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

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