我在 python 中使用 OpenCV 檢測到一個棋盤:
- 計算影像的邊緣
- 計算霍夫變換
- 尋找霍夫變換的區域最大值
- 提取影像線
然后我使用findContours和drawContours功能:
im_gray = cv2.imread('redLines.png', cv2.IMREAD_GRAYSCALE)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))
morphed = cv2.dilate(im_gray, kernel, iterations=1)
(ret, thresh) = cv2.threshold(morphed, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(thresh, contours, -1, (255, 255, 255), 3)
而且效果很好,最后一個 imshow 看起來像這樣:

現在,我正在嘗試檢測網格中的每個正方形并將其點保存在向量中的唯一索引中。
我知道我可以使用輪廓陣列來做到這一點。但是當我列印輪廓的長度時,它會快速變化,從 2 號到 112 號。
所以我猜它不能很好地識別網格。
任何幫助,將不勝感激。
uj5u.com熱心網友回復:
一種方法是使用輪廓區域過濾 形狀近似。由于正方形有 4 個角,如果輪廓有四個頂點,我們可以假設它是正方形。
檢測到的綠色方塊

孤立的正方形

import cv2
import numpy as np
# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("1.png")
mask = np.zeros(image.shape, dtype=np.uint8)
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY cv2.THRESH_OTSU)[1]
# Remove noise with morph operations
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
invert = 255 - opening
# Find contours and find squares with contour area filtering shape approximation
cnts = cv2.findContours(invert, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx) == 4 and area > 100 and area < 10000:
x,y,w,h = cv2.boundingRect(c)
cv2.drawContours(original, [c], -1, (36,255,12), 2)
cv2.drawContours(mask, [c], -1, (255,255,255), -1)
cv2.imshow("original", original)
cv2.imshow("mask", mask)
cv2.waitKey()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/462342.html
標籤:Python 图片 opencv 图像处理 计算机视觉
上一篇:基于大空白區域對掃描影像進行切片
下一篇:從影像中找到小缺陷
