python - 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.
解决方案
这是在 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
推荐阅读
- snappydata - 无法设置多节点集群
- ios - Fastlane 匹配构建 adhoc 和 appstore
- javascript - Jquery 输出显示未定义
- php - Laravel 关系 whereRaw 约束内部 with() 方法
- vue.js - Axios 变成了 Unhandled Promise Rejection with ie9
- c# - 如何正确使用 String.skip 函数?
- c# - ASP.NET MVC Web 系统发布到多域
- material-components - MDCTabBarViewController 获取栏到顶部位置
- python-3.x - chainer CNN 输入形状中的批量大小
- android - 使用圆形进度条显示记录进度