【问题标题】:How to convert array to Gray Scale Image output?如何将数组转换为灰度图像输出?
【发布时间】:2022-11-04 16:00:57
【问题描述】:
我有 txt 中的数据。我应该如何将数据转换为灰度图像输出?谢谢!
行数为 2378,列数为 5362。
我是python的菜鸟。我试过这个,但没有用。
from numpy import *
from PIL import Image
def rdnumpy(txtname):
f = open(txtname)
line = f.readlines()
lines = len(line)
for l in line:
le = l.strip('\n').split(' ')
columns = len(le)
A = zeros((lines, columns), dtype=int)
A_row = 0
for lin in line:
list = lin.strip('\n').split(' ')
A[A_row:] = list[0:columns]
A_row += 1
return A
A = rdnumpy('oop.txt')
im = Image.fromarray(array)
im = im.convert('L')
im.save('T7.png')
【问题讨论】:
标签:
python
image
grayscale
【解决方案1】:
您的代码稍作改动(参见代码中的# <<<):
from numpy import *
from PIL import Image
def rdnumpy(txtname):
f = open(txtname)
line = f.readlines()
lines = len(line)
for l in line:
le = l.strip('
').split(' ')
columns = len(le)
A = zeros((lines, columns), dtype=uint8) # <<< uint8
A_row = 0
for lin in line:
list = lin.strip('
').split(' ')
A[A_row:] = list[0:columns]
A_row += 1
return A
A = rdnumpy('PIL_imgFromText.txt')
im = Image.fromarray(A) # <<< A
im = im.convert('L')
im.save('PIL_imgFromText.png')
在“PIL_imgFromText.txt”的情况下创建
100 128 156
200 225 255
以下灰度图像(放大):
附言
下面建议如何进一步改进函数的代码:
import numpy as np
def rdnumpy_improved(txtname):
lst = []
with open(txtname) as f:
lines = f.readlines()
imgSizeY = len(lines)
imgSizeX = len(lines[0].strip('
').split(' '))
for line in lines:
lst_c = line.strip('
').split(' ')
assert imgSizeX == len(lst_c)
lst += lst_c
A = np.array(lst, dtype=uint8).reshape((imgSizeY, imgSizeX))
return A
最后,如何使用 numpy.loadtxt() 函数将整个代码缩短为单行代码(如另一个答案中所建议)
import numpy as np
from PIL import Image
Image.fromarray(np.loadtxt('PIL_imgFromText.txt', dtype=np.uint8)).save('PIL_imgFromText.png')
【解决方案2】:
首先,制作一个示例文本文件,因为没有提供问题。
import numpy as np
# Make a 10x8 pixel image of increasing numbers
im = np.arange(80).reshape((8,10))
# Save in same format as OP in file called "data.txt"
np.savetxt('data.txt', im, fmt="%d")
看起来像这样:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
现在来回答这个问题。您可以使用 Numpy 非常简单有效地加载图像,然后制作成图像并像这样保存:
from PIL import Image
# Load image from text file, make into "PIL Image", save
im = np.loadtxt('data.txt', dtype=np.uint8)
pi = Image.fromarray(im)
pi.save('result.png')
结果如下:
或者,如果你喜欢单行:
Image.fromarray(np.loadtxt('data.txt', dtype=np.uint8)).save('result.png')
【解决方案3】:
尝试使用 cv2 !
cvtColor() 功能可以将创辉图像转为灰度图像。
这里的第一步是将您的文本文件转换为图像文件(尝试.jpg)。尝试显示您的图像以查看它是否有效,这必须是彩色图片。
完成后,使用cv2 将彩色图像变为灰色图像,然后再次显示以查看结果。
您可以使用cv2.imshow('windows_name', image) 来显示图像。
import cv2
img = cv2.imread(im)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Gray Scale Image', img)
你的形象图像现在是灰色的。
如果您未能将文本文件转换为图像,请告诉我。
希望它有所帮助:)