0
我試圖區分長方形,梯形和半圓形。所以我所做的是在形狀周圍畫一個輪廓,然後畫一個旋轉的矩形。之後,我找到了輪廓和旋轉矩形的面積並取其比率。使用這個比率,我會確定形狀,因爲它對於前面提到的三種形狀是不同的。無法獲得適當的輪廓
(如果任何人有更魯棒的方法這三個區分這將受到讚賞。)
編輯的問題。我無法在圖像周圍畫出適當的輪廓。 下面是輸入和輸出圖像:
這裏是我的代碼提前
import cv2
import numpy as np
img = cv2.imread('h4.JPG')
cv2.imshow('Input',img)
#img = cv2.resize(img, None, fx=0.2,fy=0.2)
img = cv2.GaussianBlur(img, (11,11), 0)
img = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)
im = img.copy()
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,0,255,cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
max = 0
for c in contours:
area = cv2.contourArea(c)
print area
if(np.any(max <= area)):
max = c
A, B, C = cv2.minAreaRect(c)
rotrect = cv2.minAreaRect(c)
box = cv2.cv.BoxPoints(rotrect)
box = np.int0(box)
cv2.drawContours(im, contours, 0, (0,255,0), 2)
cv2.drawContours(im, [box], 0, (0,0,255), 2)
areaS = cv2.contourArea(contours[0])
areaR = B[0]*B[1]
Ratio = areaS/areaR
print "Shape Area: ",areaS
print "Shape Rect: ",areaR
print "Ratio: ",Ratio
cv2.imshow('Output',im)
if cv2.waitKey() and 0xff == 27:
cv2.destroyAllWindows()
感謝。
使用較高的閾值:'RET,脫粒= cv2.threshold(imgray,127255,cv2.THRESH_BINARY)' 。您_denoising_創建了非零像素,這些像素被'findContours'視爲_foreground_ – Miki
Thanks @Miki。它有幫助。但可以請告訴我爲什麼你特別選擇了127作爲閾值 – StupidGuy
某種程度上足夠高以去除低值(幾乎是黑色),但不能太高以去除高值(幾乎是白色)。 127在中間;)。從30到220的任何事情都可能工作得很好 – Miki