-3

I create code convert an image to binary number and save to file but I need after that Vice versa this method. Means convert binary numbers to image file.

from PIL import Image

# Load the image
img = Image.open("image.jpg")

# Convert the image to grayscale
img = img.convert("L")

# Get the pixel values as a list of tuples
pixels = list(img.getdata())

# Convert each pixel value to binary and concatenate them into a string
binary_str = ''.join(['{0:08b}'.format(pixel) for pixel in pixels])

# Save the binary data to a text file
with open("image_data.txt", "w") as f:
    f.write(binary_str)

Thanks in advance.

My code just convert image file to binary numbers. I need vice versa of this code, thanks.

  • 1
    Does [this answer your question](https://stackoverflow.com/questions/31883432/converting-jpeg-string-to-pil-image-object) – Shorn Mar 09 '23 at 06:49

1 Answers1

0

You need to know the size of the image to do so, you can for instance store it at the end of the .txt file. And naturally, you can only reconstruct a grayscale image since the conversion from rgb to grayscale is not inversible. It gives something like so in the idea:

size = img.size

arr = []
for i in range(0, len(binary_str), 8):
    arr.append(int(binary_str[i:i+8], 2))

a = np.asarray(arr).reshape(size[::-1]).astype(np.uint8)

im = Image.fromarray(a)
im.save("gray_image.jpg")
Jon99
  • 56
  • 3