2016-12-27 43 views
0

下面的圖片將說明我想要什麼。如何在python中使用opencv對圖像進行偏斜校正?

圖像包含4個參考矩形,它是圖像去扭曲的基礎。假設Image包含一些其他信息,如文本,圓形和矩形。現在,我想寫一個腳本來拉直基於四個矩形的圖像。我的結果圖像應該是拉直的。所以我可以在刪除它之後提取一些信息。 我正在使用OpenCV python,請告訴我一種方法來完成此操作。 請以OpenCV Python爲例展示一些代碼。 enter image description here之後,它一定是像enter image description here

+0

使用opencv的'findHomography'函數找到匹配點,然後使用'warpPerspective'去偏移它。 –

+0

@Optimus 1072它是真正的gud解決方案,但單應性是像源到目的地的固定點。在我的情況下,四個參考矩形不會隨着圖像的變化而被修復。由於圖像模板具有相似的矩形,但不是固定點。所以我需要一些代碼/方法來糾正偏差。 –

+0

我想我還沒有正確理解你的問題。你是否需要算法來找到目標區域,如果不是的話,那麼Homography將起作用,因爲你可以在四個角落(目的地)找到目標四個矩形,否則問題不是關於糾偏。 –

回答

1

我終於解決了它。

contours, hierarchy = cv2.findContours(img_dilate.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 

points=[] 
i=0 
for contour in contours: 
    area = cv2.contourArea(contour) 
    if area > 10 and area < 800: 
     x,y,w,h = cv2.boundingRect(contour) 
     cv2.rectangle(img_dilate,(x,y),(x+w,y+h),(0,255,0),2) 
     center = (int(x),int(y)) 
     position = (center[0], center[1]) 
     points.append(position) 
     print position,i 
     text_color = (255,0,255) 
     cv2.putText(resized,str(i+1), position, cv2.FONT_HERSHEY_SIMPLEX, 0.5, text_color, 2) 
     i=i+1 
pnts = np.array(points) 
rect = cv2.minAreaRect(pnts) 
box = cv2.cv.BoxPoints(rect) 
box = np.int0(box) 
cv2.drawContours(resized,[box],0,(0,255,0),2) 

root_mat = cv2.getRotationMatrix2D(rect[0], angle , 1) 
rotated = cv2.warpAffine(resized, root_mat, dim, flags=cv2.INTER_CUBIC) 
cv2.getRectSubPix(rotated, dim, center) 
相關問題