首页 > 解决方案 > How Can I Detect If There are Secondary Objects in an Image

问题描述

I am looking for a way to detect if there are secondary objects in an image or if the image just has the one main object. I've done a bit of research, but I haven't been able to find anything quite like what I am looking for.

An example image would be:

The main object being the two detergent bottles since they overlap and the secondary object would be the "2 pack" pop up bubble in the top right. I would expect this image to return something like: "This image has secondary objects" or a count of the objects.

标签: pythonopencv

解决方案


这是在 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



推荐阅读