0

## opencv矩形辨識的問題?提取矩形和濾除雜訊?

https://i.imgur.com/9EOw2Lx.png

1.先把圖做濾波

2.把濾出來的圖做灰度化

3.把灰度化的圖做二值化

4.對二值化的圖做findContours

5.對findContours的結果做邊緣逼近approxPolyDP

6.取得approxPolyDP的結果approx
approx陣列長度如果等於4代表是矩形

result中我用黃色圈起來的東西

``````import cv2

#選擇外接的webcam
cap = cv2.VideoCapture(0)

c = 1
timeF = 10  # frame time

while(1):
# 從攝影機擷取一張影像
if (c % timeF == 0 or c % timeF == 5):# frame 限制

dst = cv2.pyrMeanShiftFiltering(frame, 10, 50)#濾波
gray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)#灰度
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)#二值化

cv2.imshow("ShiftFiltering", dst)
cv2.imshow("threshold", thresh)

image, cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

for i in cnts:

#輪廓近似
peri = cv2.arcLength(i, True)
approx = cv2.approxPolyDP(i, 0.01*peri, True)

if len(approx) == 4:

start_point = (approx[0][0][0], approx[0][0][1])
end_point = (approx[2][0][0], approx[2][0][1])
color = (255, 0, 0)
image = cv2.rectangle(frame, start_point, end_point, color, 2)
cv2.imshow("result", image)

c = c + 1

if cv2.waitKey(1) & 0xFF == ord('q'):
final = image
break

# 釋放攝影機
cap.release()
# 關閉所有 OpenCV 視窗
cv2.destroyAllWindows()
cv2.imshow("final", final)
cv2.waitKey(0)
``````
fillano iT邦超人 1 級 ‧ 2020-01-07 16:06:37 檢舉

### 1 個回答

0
jwaiting
iT邦新手 5 級 ‧ 2020-01-10 20:48:04

findContours應該是找尋物件的輪廓

approxPolyDP

jwaiting iT邦新手 5 級 ‧ 2020-01-13 19:17:33 檢舉

start_point = (approx[0][0][0], approx[0][0][1])
end_point = (approx[2][0][0], approx[2][0][1])