【问题标题】:Translate pixels from cropped section of image to original image OpenCV将像素从图像的裁剪部分转换为原始图像 OpenCV
【发布时间】:2018-01-08 19:24:52
【问题描述】:

我在 Python 中使用 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 绘图功能来编辑 subImage,我怎样才能将这些相同的绘图放回 mainImage 的相应像素上?例如(如果使用我提供的解释图像中的图像形状)我在 subImage 上绘制了一个直立的笑脸,我如何将其转换为 mainImage 上正确位置的正确定向的对角笑脸?

【问题讨论】:

    标签: python image opencv image-processing image-manipulation


    【解决方案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!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 2014-06-01
      • 1970-01-01
      • 2017-08-04
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多