python-3.x 当我使用txt时,枕头图像的颜色是错误的numpy数组

gkl3eglg  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(113)

首先,我将一个图像转换为numpy数组,并将其写入文本文件,这部分工作正常
问题是当我复制txt内容并将其动态粘贴为vector并显示图像时。颜色显示错误。
enter image description hereenter 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)

`
我得把颜色弄对

46qrfjad

46qrfjad1#

看起来问题是图像数组在文本文件中保存为字符串数组而不是整数数组。当您读取文本文件并将其转换回数组时,这些值被解释为字符串,从而导致图像显示时出现错误的颜色。
这个问题的一个解决方案是将文本文件中的数组保存为整数数组,而不是字符串数组。可以使用numpy.savetxt()函数将数组以指定的格式保存到文本文件中。下面的示例说明如何修改代码,将数组保存为文本文件中的整数:

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)
    # Save the array as integers in the text file
    numpy.savetxt('img_array.txt', image, fmt='%d')

def show_imagem(array):
    # Create a NumPy array from the text file
    arry = numpy.loadtxt('img_array.txt', dtype=int)
    
    # 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)

在这段代码中,img_to_txt_array()函数使用numpy.savetxt()函数将图像数组作为整数保存在文本文件中。show_imagem()函数使用numpy.loadtxt()函数从文本文件中读取数组,然后创建并显示数组中的图像。这应该可以解决图像中颜色错误的问题。

相关问题