Search code examples
pythonpython-imaging-librarypixelrgbtxt

Make image from uint8 RGB pixel data


I am trying to make a library related to RGB pixel data, but cannot seem to save the image data correctly.

Image

That is my output image. This is my code:

pixelmanager.py

from PIL import Image
import numpy as np

class MakeImgFromPixelRGB:
    def createIMG(PixelArray: list, ImgName: str, SaveImgAsFile: bool):
        # Convert the pixels into an array using numpy
        array = np.array(PixelArray, dtype=np.uint8)
        if SaveImgAsFile == True:
            new_image = Image.fromarray(array)
            new_image.save(ImgName)
class getPixelsFromIMG:
    def __init__(self, ImagePath):
        im = Image.open(ImagePath, 'r')
        width, height = im.size
        pixel_values = list(im.getdata())
        self.output = pixel_values

test.py

import pixelmanager

a = pixelmanager.getPixelsFromIMG(ImagePath="download.jpg")

pixelmanager.MakeImgFromPixelRGB.createIMG(a.output, "output.png", True)

with open("output.txt", "w") as f:
    for s in a.output:
        f.write(str(s) + "," + "\n")

I have tried to de-scale the image in paint.net and also tried to mess with the uint size.


Solution

  • Mark Setchell was ALMOST correct. His code did help me get an image, but it was repeated 4 times in one.

    Mark's line of code had a switchup (with h as height and w as width):

    array = np.array(PixelArray, dtype=np.uint8).reshape(h,w,3)
    

    This is my line of code:

    array = np.array(PixelArray, dtype=np.uint8).reshape(w, h, 3)