Python 如何从包含二进制像素数据的数组列表创建新图像
在这里,我使用PIL库来读取和操作图像。我很困惑,在转换为二进制图像后,如何从包含二进制像素数据的数组列表中创建新图像 我已经试过了,但是得到的图像是RGB类型的,不是二进制图像。以下是我编写的代码:Python 如何从包含二进制像素数据的数组列表创建新图像,python,image,arraylist,binary,python-imaging-library,Python,Image,Arraylist,Binary,Python Imaging Library,在这里,我使用PIL库来读取和操作图像。我很困惑,在转换为二进制图像后,如何从包含二进制像素数据的数组列表中创建新图像 我已经试过了,但是得到的图像是RGB类型的,不是二进制图像。以下是我编写的代码: from PIL import Image import numpy as np img = Image.open('data_train/ga.jpeg') pixels = img.load() width, height = img.size all_pixels = [] for
from PIL import Image
import numpy as np
img = Image.open('data_train/ga.jpeg')
pixels = img.load()
width, height = img.size
all_pixels = []
for x in range(width):
for y in range(height):
hpixel = pixels[x, y]
img_gray = (0.2989 * hpixel[0]) + (0.5870 * hpixel[1]) + (0.1140 * hpixel[2])
if img_gray >= 110:
all_pixels.append('1')
else:
all_pixels.append('0')
data_isi = {'0': 0,
'1': 255}
data = [data_isi[letter] for letter in all_pixels]
img_new = Image.fromarray(data)
img_new.save('data_train/gabiner.jpeg')
更新的答案 由于需要为循环使用
,因此可以使用类似以下内容:
#!/usr/bin/env python3
from PIL import Image
# Load image and get dimensions
img = Image.open('start.jpg').convert('RGB')
width, height = img.size
# Actually load input pixels, else PIL is too lazy
imi = img.load()
# List of result pixels
imo = []
for y in range(height):
for x in range(width):
R, G, B = imi[x, y]
gray = (0.2989 * R) + (0.5870 * G) + (0.1140 * B)
if gray >= 110:
imo.append(255)
else:
imo.append(0)
# Make output image and put output pixels into it
result = Image.new('L', (width,height))
result.putdata(imo)
# Save result
result.save('result.png')
#!/usr/local/bin/python3
from PIL import Image
# Load image and make greyscale
im = Image.open('image.png').convert('L')
# Threshold to make black and white
thr = im.point(lambda p: p > 110 and 255)
# Save result
thr.save('result.png')
这将打开此开始图像:
在这一结果中:
原始答案
您似乎正在将图像转换为灰度并在110处设置阈值,这可以更简单、更快地完成,如下所示:
#!/usr/bin/env python3
from PIL import Image
# Load image and get dimensions
img = Image.open('start.jpg').convert('RGB')
width, height = img.size
# Actually load input pixels, else PIL is too lazy
imi = img.load()
# List of result pixels
imo = []
for y in range(height):
for x in range(width):
R, G, B = imi[x, y]
gray = (0.2989 * R) + (0.5870 * G) + (0.1140 * B)
if gray >= 110:
imo.append(255)
else:
imo.append(0)
# Make output image and put output pixels into it
result = Image.new('L', (width,height))
result.putdata(imo)
# Save result
result.save('result.png')
#!/usr/local/bin/python3
from PIL import Image
# Load image and make greyscale
im = Image.open('image.png').convert('L')
# Threshold to make black and white
thr = im.point(lambda p: p > 110 and 255)
# Save result
thr.save('result.png')
欢迎来到Stackoverflow。请对代码使用正确的格式。在当前格式中,您的代码被分解为多个比特和片段。我如何为我的代码使用正确的格式?谢谢,但我的讲师要求我编写直接操作像素的代码,因此我需要一份关于如何直接操作像素的参考资料,以便能够生成灰度图像。你能帮帮我吗?我强迫自己使用一些来进行循环-请再看一看。如何在PIL中将图像保存为单通道颜色?就像我做的那样。将图像创建为单通道image.new('L',…)
然后save()