Search code examples
pythonimageopencvndimage

Rotate an image without averaging pixel values


Is it possible to rotate an image and keep the true values? When I rotate a black and white image I get back grey values. Can I rotate without averaging the pixel values? I can almost do it manually by using np.where() but it gets difficult when there are more than 2 pixel values.

Code:

import matplotlib.image as mpimg 
import matplotlib.pyplot as plt 
from scipy import ndimage
import cv2

filename = 'rot square.png'  

img = cv2.imread('square test.png') 
img_rot = ndimage.rotate(img, 10, reshape = False)
cv2.imwrite(filename, img_rot)

Original Image

Original Image

Rotated Image

Rotated Image

Averaged Values

Averaged Values

True Values

True Values


Solution

  • Here:

    from PIL import Image
    
    img = Image.open('original.png')
    rotated = img.rotate(45)
    rotated.save('rotated.png')