Python PIL Rotate (Image Result Quality)

435 views Asked by At

I'm using Python 3.11 with Pillow 9.3.0 and OpenCV 4.6.0.66. I want to make sure if I doing 90 degree rotate with PIL, the quality of image is same.

ret = False
frame = None
camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
if camera.isOpened():
    camera.set(cv2.CAP_PROP_FPS, 30.0)
    camera.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('m', 'j', 'p', 'g'))
    camera.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G'))
    camera.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
    camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
    for _ in range(0, 11, 1):
        ret, frame = camera.read()
    if ret:
        cv2.imwrite("1.jpg", frame)
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        pil_im = Image.fromarray(frame)
        buffer_ = io.BytesIO()
        pil_im.save(buffer_, format="JPEG", quality=95)
        print(f"Before Rotate: {buffer_.getbuffer().nbytes}")
        pil_im = pil_im.rotate(90, Image.Resampling.NEAREST, expand=True)
        buffer_ = io.BytesIO()
        pil_im.save(buffer_, format="JPEG", quality=95)
        print(f"After Rotate: {buffer_.getbuffer().nbytes}")
        pil_im.save("1_edit.jpg", format="JPEG", quality=95)

The result of that program:

Before Rotate: 269183 After Rotate: 268793

Are this output indicate that the quality image is drop? Thanks in advance!

1

There are 1 answers

2
Mark Setchell On BEST ANSWER

The length in bytes of a JPEG file is not a very accurate indicator of its quality. It can be affected by other things including the content of your image.

The statement that an image may be able to be rotated through 90 degrees without loss is correct since the raster grids will coinicide and no resampling will be required. If you want to convince yourself of this, you could try rotating the image back through -90 degrees and comparing the result with the original to prove there is no loss/difference - note that I am talking about rotating the originally captured frame with no JPEGs involved.