问题
I want to crop to an object in my image, so that only the colored object remains. How can I do it in python in the most efficient way?
Basically the image has black (0,0,0) background but different colors for an object. I want to crop to the object in order to drop the useless background.
I know cv2 has the resize() function but they cannot detect whether it is the background or not. I can also loop the whole image to find the position but that is too slow.
回答1:
Finally I have find an API to do the work.
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
来源:https://stackoverflow.com/questions/55495807/how-to-crop-object-in-the-image-on-the-particular-background-color-in-opencv-pyt