2017-08-01 368 views
1

我在Python中使用OpenCV。我已經使用下面的代碼來選擇並複製的主圖像的一個部分成子圖像:將像素從圖像的裁剪部分轉換爲原始圖像OpenCV

boundingBoxRotatedRect = cv2.minAreaRect(boxPoints) 
if boundingBoxRotatedRect[2] < -45: 
    boundingBoxRotatedRect = (boundingBoxRotatedRect[0], (boundingBoxRotatedRect[1][1],boundingBoxRotatedRect[1][0]), boundingBoxRotatedRect[2] + 90) 
M = cv2.getRotationMatrix2D(boundingBoxRotatedRect[0], boundingBoxRotatedRect[2], 1.0) 
size = np.int0(boundingBoxRotatedRect[1]) 
size = (size[0],size[1]) 
dst = cv2.warpAffine(mainImage, M, (mainImage.shape[1], mainImage.shape[0])) 
subImage = cv2.getRectSubPix(dst, size, boundingBoxRotatedRect[0]) 

凡boxPoints爲4點構成周圍區域的邊界框的陣列,以從所述被裁剪主圖像,boundingBoxRotatedRect是表示爲旋轉矩形對象的相同框,M是旋轉矩陣,size是邊界框的寬度/高度,mainImage是從中裁剪的主圖像,subImage最終是最終圖像已從主圖像中裁剪出來。下面鏈接的圖片進一步解釋了發生的事情。

Explanation Image

我的問題是:如果我使用OpenCV的繪圖功能來編輯子圖像,我怎樣才能把這些相同的圖紙放回mainImage對應的像素?舉例來說(如果在我提供的解釋圖像中使用圖像形狀),我在子圖像上繪製直立的笑臉,如何將它轉換成正確位置的對角笑臉,並放置在mainImage的正確位置上?

回答

1

找到了解決方案。單應!

替換上述代碼用:

#If bottomLeft = true, boxPoints[0] corresponds to btm-lft corner of subImage. 
#If bottomLeft = false, boxPoints[0] corresponds to btm-right corner of subImage. 
bottomLeft = True 

boundingBoxRotatedRect = cv2.minAreaRect(boxPoints) 
if boundingBoxRotatedRect[2] < -45: 
    boundingBoxRotatedRect = (boundingBoxRotatedRect[0], (boundingBoxRotatedRect[1][1],boundingBoxRotatedRect[1][0]), boundingBoxRotatedRect[2] + 90) 
    bottomLeft = False 
M = cv2.getRotationMatrix2D(boundingBoxRotatedRect[0], boundingBoxRotatedRect[2], 1.0) 
size = np.int0(boundingBoxRotatedRect[1]) 
size = (size[0],size[1]) 
dst = cv2.warpAffine(mainImage, M, (mainImage.shape[1], mainImage.shape[0])) 
subImage = cv2.getRectSubPix(dst, size, boundingBoxRotatedRect[0]) 

#Get homography matrix 
if bottomLeft: 
    pts_src = np.array([[0, size[0] - 1], [0, 0], [size[1] - 1, 0],[size[1] - 1, size[0] - 1]]) 
else: 
    pts_src = np.array([[size[1] - 1, size[0] - 1], [0, size[0] - 1], [0, 0], [size[1] - 1, 0]]) 
pts_dst = boxPoints 
h, status = cv2.findHomography(pts_src, pts_dst) 


## BELOW, REPLACE "[x, y], [X2, Y2], ...]" WITH LIST OF POINTS FROM SUBIMAGE TO BE TRANSLATED TO MAINIMAGE 
a = np.array([[x, y], [X2, Y2], ...] dtype='float32') 
a = np.array([a]) 
pointsOut = cv2.perspectiveTransform(a, h) 
pointsOut = pointsOut[0] 

#Then use the points in pointsOut to draw whatever you want!