lilohuang/PyTurboJPEG

encoding a grayscale image

carlodri opened this issue · 2 comments

Hi and thank you for your work on this great package.

I'm trying to save a simple 2D numpy array into a grayscale image, using this test code:

import numpy as np

from turbojpeg import TJPF_GRAY, TurboJPEG

jpeg = TurboJPEG()

rng = np.random.default_rng()
image = rng.integers(low=0, high=255, dtype=np.uint8, size=(3008, 4112))

with open("test.jpg", "wb") as output_jpeg_file:
    output_jpeg_file.write(jpeg.encode(img_array=image, pixel_format=TJPF_GRAY))

and what I get is the following error (obviously, because the input array has only 2 dimensions):

    height, width, _ = img_array.shape
ValueError: not enough values to unpack (expected 3, got 2)

I would expect this code to work, since if I pass pixel_format=TJPF_GRAY a 2D array should suffice to give all the necessary data to the encoder. Even if I try to augment the dimensions yielding three identical channels (using np.dstack), I get a OSError: Unsupported color conversion request error on the encode command.

What am I doing wrong? What can be done to obtain a grayscale JPEG?

Hi @carlodri

You need to create the numpy array dimension like below for grayscale image, and set the jpeg subsample to be TJSAMP_GRAY. I will close this ticket and please let me know if it still doesn't work for you.

import numpy as np
from turbojpeg import TJPF_GRAY, TJSAMP_GRAY, TurboJPEG

jpeg = TurboJPEG()
rng = np.random.default_rng()
image = rng.integers(low=0, high=255, dtype=np.uint8, size=(3008, 4112, 1))

with open("test.jpg", "wb") as output_jpeg_file:
    output_jpeg_file.write(jpeg.encode(img_array=image, pixel_format=TJPF_GRAY, jpeg_subsample=TJSAMP_GRAY))

Best,
Lilo

Thanks a lot @lilohuang it works perfectly!