且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在opencv-python中的特定背景颜色上裁剪图像中的对象?

更新时间:2023-01-15 18:18:34

最后,我找到了一个API

Finally I have find an API to do the work.

使用cv2.findContours()从蒙版图像(具有相应颜色的对象)中获取对象的位置,并直接用numpy对其进行剪切。

use cv2.findContours() to get the position of the object from the mask image (an object with a corresponding color) and directly cut it with numpy.

def cut_object(rgb_image,mask_image,object_color):
    """This function is used to cut a specific object from the pair RGB/mask image."""
    rgb_image=cv2.imread(rgb_image)
    mask_image=cv2.imread(mask_image)
    mask_image=cv2.cvtColor(mask_image,cv2.COLOR_BGR2RGB)

    # Create mask image with the only object
    object_mask_binary=cv2.inRange(mask_image,object_color,object_color)
    object_mask=cv2.bitwise_and(mask_image,mask_image,mask=object_mask_binary)

    # Detect the position of the object
    object_contour=cv2.cvtColor(object_mask,cv2.COLOR_BGR2GRAY)
    object_position,c=cv2.findContours(object_contour,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    object_position=np.array(object_position).squeeze()
    hmin,hmax=object_position[:,:1].min(),object_position[:,:1].max()
    wmin,wmax=object_position[:,1:2].min(),object_position[:,1:2].max()

    # Cut the object from the RGB image
    crop_rgb=rgb_image[wmin:wmax,hmin:hmax]

    return crop_rgb