How to crop an image in OpenCV using Python

后端 未结 9 2269
面向向阳花
面向向阳花 2020-11-22 08:45

How can I crop images, like I\'ve done before in PIL, using OpenCV.

Working example on PIL

im = Image.open(\'0.png\').convert(\'L\')
im = im.crop((1         


        
9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 09:12

    Alternatively, you could use tensorflow for the cropping and openCV for making an array from the image.

    import cv2
    img = cv2.imread('YOURIMAGE.png')
    

    Now img is a (imageheight, imagewidth, 3) shape array. Crop the array with tensorflow:

    import tensorflow as tf
    offset_height=0
    offset_width=0
    target_height=500
    target_width=500
    x = tf.image.crop_to_bounding_box(
        img, offset_height, offset_width, target_height, target_width
    )
    

    Reassemble the image with tf.keras, so we can look at it if it worked:

    tf.keras.preprocessing.image.array_to_img(
        x, data_format=None, scale=True, dtype=None
    )
    

    This prints out the pic in a notebook (tested in Google Colab).


    The whole code together:

    import cv2
    img = cv2.imread('YOURIMAGE.png')
    
    import tensorflow as tf
    offset_height=0
    offset_width=0
    target_height=500
    target_width=500
    x = tf.image.crop_to_bounding_box(
        img, offset_height, offset_width, target_height, target_width
    )
    
    tf.keras.preprocessing.image.array_to_img(
        x, data_format=None, scale=True, dtype=None
    )
    

提交回复
热议问题