How to crop an image in OpenCV using Python

后端 未结 9 2075
面向向阳花
面向向阳花 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:00

    Below is the way to crop an image.

    image_path: The path to the image to edit

    coords: A tuple of x/y coordinates (x1, y1, x2, y2)[open the image in mspaint and check the "ruler" in view tab to see the coordinates]

    saved_location: Path to save the cropped image

    from PIL import Image
        def crop(image_path, coords, saved_location:
            image_obj = Image.open("Path of the image to be cropped")
                cropped_image = image_obj.crop(coords)
                cropped_image.save(saved_location)
                cropped_image.show()
    
    
    if __name__ == '__main__':
        image = "image.jpg"
        crop(image, (100, 210, 710,380 ), 'cropped.jpg')
    
    0 讨论(0)
  • 2020-11-22 09:02

    here is some code for more robust imcrop ( a bit like in matlab )

    def imcrop(img, bbox): 
        x1,y1,x2,y2 = bbox
        if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]:
            img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2)
        return img[y1:y2, x1:x2, :]
    
    def pad_img_to_fit_bbox(img, x1, x2, y1, y2):
        img = np.pad(img, ((np.abs(np.minimum(0, y1)), np.maximum(y2 - img.shape[0], 0)),
                   (np.abs(np.minimum(0, x1)), np.maximum(x2 - img.shape[1], 0)), (0,0)), mode="constant")
        y1 += np.abs(np.minimum(0, y1))
        y2 += np.abs(np.minimum(0, y1))
        x1 += np.abs(np.minimum(0, x1))
        x2 += np.abs(np.minimum(0, x1))
        return img, x1, x2, y1, y2
    
    0 讨论(0)
  • 2020-11-22 09:04

    to make it easier for you here is the code that i use :

    w, h = image.shape
    top=10
    right=50
    down=15
    left=80
    croped_image = image[top:((w-down)+top), right:((h-left)+right)]
    plt.imshow(croped_image, cmap="gray")
    plt.show()
    
    0 讨论(0)
  • 2020-11-22 09:12

    Note that, image slicing is not creating a copy of the cropped image but creating a pointer to the roi. If you are loading so many images, cropping the relevant parts of the images with slicing, then appending into a list, this might be a huge memory waste.

    Suppose you load N images each is >1MP and you need only 100x100 region from the upper left corner.

    Slicing:

    X = []
    for i in range(N):
        im = imread('image_i')
        X.append(im[0:100,0:100]) # This will keep all N images in the memory. 
                                  # Because they are still used.
    

    Alternatively, you can copy the relevant part by .copy(), so garbage collector will remove im.

    X = []
    for i in range(N):
        im = imread('image_i')
        X.append(im[0:100,0:100].copy()) # This will keep only the crops in the memory. 
                                         # im's will be deleted by gc.
    

    After finding out this, I realized one of the comments by user1270710 mentioned that but it took me quite some time to find out (i.e., debugging etc). So, I think it worths mentioning.

    0 讨论(0)
  • 2020-11-22 09:12

    this code crop an image from x=0,y=0 position to h=100,w=200

    import numpy as np
    import cv2
    
    image = cv2.imread('download.jpg')
    y=0
    x=0
    h=100
    w=200
    crop = image[y:y+h, x:x+w]
    cv2.imshow('Image', crop)
    cv2.waitKey(0) 
    
    0 讨论(0)
  • 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
    )
    
    0 讨论(0)
提交回复
热议问题