[英]Find contours of a square table (matrix shape) in an image using Python OpenCV
我是新手,我想知道如何使用 Python OpenCV(cv2 庫)找到如下圖像的輪廓:
我准備在每個方格中填入一個數字,然后轉換成numpy數組,所以我想我需要先弄清楚如何得到矩陣中每個方格的輪廓(可能是圖片中方格的坐標)
我嘗試使用一些代碼片段:
img = cv2.imread(img_path, 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
binary = cv2.bitwise_not(gray)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for contour in contours:
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
但它不起作用
嘗試這個:
img = cv2.imread(img_path, 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gauss = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 3, 0)
ret,thresh = cv2.threshold(gauss,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)
rev=255-thresh
_ ,contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST ,cv2.CHAIN_APPROX_SIMPLE)
print(contours)
min_rect_len = 15
max_rect_len = 20
for contour in contours:
(x, y, w, h) = cv2.boundingRect(contour)
if h>min_rect_len and w>min_rect_len:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 1)
cv2.imwrite(img_path[:-4] + "_with_contours.jpg", img)
也許使用霍夫線會做的工作:-> 在這里檢查
問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.