pythonopencvimage-rotationimutils

Remove the black border and keep the image size same in python


I am rotating an image 45 degree. When I rotate the image it has a black border and the image size changes from 256x256 to 364x364. I want to remove the values of this black border and keep the size 256. In pillow if I put fill color then the black border will go away but the size is still the same. Is there any way that I can remove the black border and retain the original shape

code to rotate

path = "E:\\download\\1.jpeg"
image = cv2.imread(path)
rotated = imutils.rotate_bound(image, -33)

Original Image

Original Image

Rotate image

Rotated image


Solution

  • you can try to crop the image as much as part of the image you want. Although the cropping in python is possible in the form of pixels. Hence, you can try to crop the image as much is required. The following code might help you to crop

    im=Image.open(r"specify the path of the image")`
    

    width, height = im.size

    left = "specify the value in pixels"
    top = "specify the value in pixels"
    right = "specify the value in pixels"
    bottom = "specify the value in pixels"
    # Cropped image of above dimension
    # (It will not change original image)
    im1 = im.crop((left, top, right, bottom))
    #im1.show()
    im1.save('specify destination path')