首页 文章

感兴趣的区域与透明背景的小图像

提问于
浏览
2

我想从给定掩码的图像中提取感兴趣区域(ROI),并将其保存在调整为ROI大小的新文件中,并使用透明背景 .

例如,给出这个图像:

enter image description here

我想得到这个:

enter image description here

这里的解决方案NumPy/OpenCV 2: how do I crop non-rectangular region?提供全尺寸的输出图像 . 如何让它输出ROI的矩形尺寸?

我可以按位 and 图像和蒙版,但我真的很困惑一个调整图像大小并将其保存为透明png的好方法 .

2 回答

  • 2

    将此图像(1.jpg)与脚本放在同一文件夹中

    enter image description here

    以下掩盖的图像:

    enter image description here

    我写了一个非常hacky的解决方案 .

    import numpy as np                                                                                                                                                                                                          
    import sys
    import cv2        
    
    image = cv2.imread('1.jpg')
    
    # mask (of course replace corners with yours)
    mask = np.zeros(image.shape, dtype=np.uint8)
    roi_corners = np.array([[(10,10), (200,200), (10,200)]], dtype=np.int32)
    white = (255, 255, 255)
    cv2.fillPoly(mask, roi_corners, white)
    
    # apply the mask
    masked_image = cv2.bitwise_and(image, mask)
    
    
    #shrink the top
    iii = 0
    #the matrix sum of back is 0
    while  not np.sum(masked_image[iii,:,:]):
            resized_top = masked_image[iii+1:,:,:]
                iii = iii + 1
    
    
    #shrink the bottom
    size_img = resized_top.shape
    iii = size_img[0]
    while not np.sum(resized_top[iii-2:iii-1,:,:]):
            resized_bottom = resized_top[0:iii-1,:,:]
                iii = iii - 1
    
    #shrink the left
    iii = 0
    while  not np.sum(resized_bottom[:,iii,:]):
            resized_left = resized_bottom[:,iii+1:,:]
                iii = iii + 1
    
    #shrink the right
    size_img = resized_left.shape
    iii = size_img[1]
    print iii
    while  not np.sum(resized_left[:,iii-2:iii-1,:]):
            resized_right = resized_left[:,0:iii-1:,:]
                iii = iii - 1
    
    
    #display your handywork
    cv2.imshow('masked image', resized_right)
    cv2.waitKey()
    cv2.destroyAllWindows()
    

    结果:

    enter image description here

  • 3

    裁剪图像可以通过实现

    cropped_img = masked_image[y1:y2, x1:x2]
    

    首先必须计算ROI的矩形边界框 .

相关问题