2017-06-13 104 views
1

image with rectangles掃描圖像上的Python,OpenCV和矩形

您好!掌握OpenCV,我遇到了一個問題:我找不到任何這些盒子然後切割。請告訴我,使用哪些過濾器和邏輯?

#!/usr/bin/env python 
import cv2 
import os 

img_path = os.path.join('img', '1.jpg') 
image = cv2.imread(img_path) 

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 
gray = cv2.bilateralFilter(gray, 11, 17, 17) 
edged = cv2.Canny(gray, 30, 200) 

cv2.imshow('gray', gray) 
cv2.waitKey(0) 

cv2.imshow('edged', edged) 
cv2.waitKey(0) 


(_, cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 

for c in cnts: 
    peri = cv2.arcLength(c, True) 
    approx = cv2.approxPolyDP(c, 0.02 * peri, True) 

    if len(approx) == 4: 
     cv2.drawContours(image, [approx], -1, (0, 255, 0), 3) 


cv2.imshow('result', image) 
cv2.waitKey(0) 

本示例查找大量的垃圾,和所有的矩形(未僅那些與背景)

編輯: OpenСV重複矩形輪廓。我怎樣才能切斷重複?

+0

到目前爲止,您嘗試了什麼? – asongtoruin

+0

我剛開始學習opencv。有一項緊迫的任務。我試圖使用canny過濾器,然後findContours – ilya

+0

發佈您的代碼(編輯它到您的文章) - 告訴我們它出錯的地方。 – asongtoruin

回答

0

您非常接近解決方案,在迭代輪廓for c in cnts:時,您基於輪廓近似的多邊形的邊數來過濾輪廓,您只需添加輪廓區域的過濾器以便刪除檢測到的較小的矩形,可以這樣做:

for c in cnts: 
    peri = cv2.arcLength(c, True) 
    approx = cv2.approxPolyDP(c, 0.02 * peri, True) 

    if len(approx) == 4 and cv2.contourArea(c) > 200: 
     cv2.drawContours(image, [approx], -1, (0, 255, 0), 3) 
+0

thx,清理所有垃圾,但問題仍然是如何不分配沒有背景的矩形 – ilya