将像素从图像的裁剪部分转换为原始图像OpenCV

问题描述:

我在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的正确位置上?

找到了解决方案。单应!

替换上述代码用:

#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!