Home > OS >  colors are wrong numpy array for pillow image when I use txt
colors are wrong numpy array for pillow image when I use txt

Time:12-07

firstly I am transforming an image into numpy array and writing it to a text file and this part is working

the problem is when i copy the txt content and dynamically paste it as vector and display the image. the colors are showing wrong.

enter image description here enter image description here

`

import cv2
import sys
import numpy
from PIL import Image

numpy.set_printoptions(threshold=sys.maxsize)

def img_to_txt_array(img):
    image = cv2.imread(img)
    # print(image)
    f = open("img_array.txt", "w")
    f.write(str(image))
    f.close()
    meuArquivo = open('img_array.txt', 'r')
    with open('img_array.txt', 'r') as fd:
        txt = fd.read()
        txt = txt.replace(" ", ",")
        txt = txt.replace('\n',',\n')
        txt = txt.replace("[,", "[")
        txt = txt.replace(',[', '[')
        txt = txt.replace(",,", ",")
        txt = txt.replace(',[', '[')
        txt = txt.replace("[,", "[")
        txt = txt.replace(",,", ",")

    with open('img_array.txt', 'w') as fd:
        fd.write(txt)
    with open('img_array.txt', 'r') as fr:
        lines = fr.readlines()
        with open('img_array.txt', 'w') as fw:
            for line in lines:
                if line.strip('\n') != ',':
                    fw.write(line)

def show_imagem(array):
    # Create a NumPy array
    arry = numpy.array(array)
    
    # Create a PIL image from the NumPy array
    image = Image.fromarray(arry.astype('uint8'), 'RGB')
    
    # Save the image
    #image.save('image.jpg')
    
    # Show the image
    image.show(image)

array = [] #paste here the txt

img_to_txt_array('mickey.png')
show_imagem(array)

`

I need to get the colors right

CodePudding user response:

Thing is, OpenCV reads images in BGR order, while PIL uses RGB order.

You may fix this at several points in your program (when reading, when saving, or when re-reading again).

For example, you can re-arrange the array, right after you read the image:

def img_to_txt_array(img):
    image = cv2.imread(img)
    image = image[:,:,::-1] ## ====> NEW. Reordering BGR to RGB

    ..... ## the rest of the function is the same 
    ..... ## (though there are other issues)

Also, rather than copy-paste the array, here is a function to read it directly from your .txt file (might NOT be optimal):

#array = [] #paste here the txt ## ==> not used anymore, see below
    
def load_array(f):
    with open(f) as data:
        ar_rows = data.readlines()
    ar_str = "".join(ar_rows)
    return eval(ar_str)
        

img_to_txt_array('mickey.png')
array = load_array('img_array.txt')
show_imagem(array)

I hope this helps.

  • Related