【发布时间】:2021-11-30 02:19:16
【问题描述】:
所以,我正在努力寻找可以在图像中看到的电子芯片上的小组件。到目前为止,我一直在努力寻找轮廓,然后应用形态学操作并绘制矩形。我附上原始的、必需的和实现的图像以及代码,以便社区可以轻松理解问题。
import cv2
import os
# Load iamge, grayscale, adaptive threshold
image = cv2.imread('4.jpg')
result = image.copy()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV,51,9)
# Fill rectangular contours
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
cv2.drawContours(thresh, [c], -1, (255,255,255), -1)
# Morph opend
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=4)
# Draw rectangles
cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 3)
cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.imshow('image', image)
cv2.waitKey()
This is the result that I am trying to achieve
任何帮助将不胜感激。谢谢
【问题讨论】:
-
仅使用一个样本很难为这个问题提供一个好的通用解决方案,如果你能收集到足够的训练数据,我建议使用像 YOLOV5 这样的检测模型,而不是采用经典方法
标签: python python-3.x opencv opencv-contour image-thresholding