Python 如何在opencv中正确选择电路板的轮廓?
我试图确定棋盘的边界(它们由一个黑条限定) 我做以下几点Python 如何在opencv中正确选择电路板的轮廓?,python,opencv,computer-vision,chess,Python,Opencv,Computer Vision,Chess,我试图确定棋盘的边界(它们由一个黑条限定) 我做以下几点 img = cv2.imread(filename) gray = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) cv2.imwrite("gray.jpg", gray) 在那之后,我不可能得到更好的结果 contours0, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2
img = cv2.imread(filename)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.imwrite("gray.jpg", gray)
在那之后,我不可能得到更好的结果
contours0, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours0:
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img, [box], -1, (255, 0, 0), 0)
cv2.imshow('contours', img)
有人能帮我吗?在Python OpenCV中有一种方法可以做到这一点。基本上,对图像设置阈值。应用一些形态学。获取外部轮廓。然后在黑色背景上画出周长高于某个阈值的最大值。重要的是,你得到了4个角落包括在内。然后得到凸包,并将其绘制为边界 输入:
阈值图像: 形态图像: 轮廓图像: 在输入副本上生成凸包:
在Python OpenCV中,有一种方法可以做到这一点。基本上,对图像设置阈值。应用一些形态学。获取外部轮廓。然后在黑色背景上画出周长高于某个阈值的最大值。重要的是,你得到了4个角落包括在内。然后得到凸包,并将其绘制为边界 输入:
阈值图像: 形态图像: 轮廓图像: 在输入副本上生成凸包:
contours0, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours0:
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img, [box], -1, (255, 0, 0), 0)
cv2.imshow('contours', img)
import cv2
import numpy as np
# read image
img = cv2.imread('chess.jpg')
# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# threshold to binary
thresh = cv2.threshold(gray, 25, 255, cv2.THRESH_BINARY)[1]
# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
morph = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,1))
morph = cv2.morphologyEx(morph, cv2.MORPH_CLOSE, kernel)
# invert morph
morph = 255 - morph
# get external contours
cnts = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
# draw white contour on black background
cntr_img = np.zeros_like(morph)
for c in cnts:
perimeter = cv2.arcLength(c, True)
if perimeter > 200:
cv2.drawContours(cntr_img, [c], 0, 255, 1)
# get all non-zero points
points = np.column_stack(np.where(cntr_img.transpose() > 0))
hull = cv2.convexHull(points)
# draw convex hull vertices on input image
result = img.copy()
cv2.polylines(result, [hull], True, (0,0,255), 2)
# save results
cv2.imwrite('chess_threshold.jpg', thresh)
cv2.imwrite('chess_morph.jpg', morph)
cv2.imwrite('chess_contour.jpg', cntr_img)
cv2.imwrite('chess_convexhull.jpg', result)
# show results
cv2.imshow('thresh', thresh)
cv2.imshow('morph', morph)
cv2.imshow('cntr_img', cntr_img)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()