Home > Software engineering >  Convert jpeg values in txt file to image
Convert jpeg values in txt file to image

Time:10-24

I'm trying in this code to convert jpeg values in txt file to jpg image. The size of captured image = 120*160 and the numbers of values in file = 2396 (I don't know why this total length).

I get this error

na = np.array(pixels, dtype=np.uint8).reshape((int(h),int(w)))
  ValueError: cannot reshape array of size 2396 into shape (120,160)

Code:

# Open image file, slurp the lot
contents = Path('C://Users//hp//Desktop//file.txt').read_text()

# Make a list of anything that looks like numbers using a regex...
# ... taking first as height, second as width and remainder as pixels
h, w, *pixels = re.findall(r'[0-9] ', contents)

# Now make pixels into Numpy array of uint8 and reshape to correct height, width and depth
na = np.array(pixels, dtype=np.uint8).reshape((int(h),int(w)))

# Now make the Numpy array into a PIL Image and save
Image.fromarray(na).save('C://Users//hp//Desktop//jp.jpg')

CodePudding user response:

There is no need for the PIL library. You already have a JPEG file.
Just convert those numbers to bytes and save them.

with open("C://Users//hp//Desktop//file.txt", "r") as f:
    data = f.read()
data = data.split(",") # split the numbers
data = [int(b) for b in data] # convert them to integers
data = data[2:] # remove width and height
data = bytes(data) # convert the array of numbers to bytes
with open("C://Users//hp//Desktop//jp.jpg", "wb") as f:
    f.write(data)

Result:

jp.jpg

Note: There appears to be missing data at the end. You might have not captured all the data.
You claim to have 2396 values, but your example has 3842.

  • Related