简体   繁体   English

从像素值的二维数组创建灰度图像

[英]Creating a gray-scale image from an 2D array of pixel values

I am trying to change the values from a gray scale PNG image and then create an image from those changed values.我正在尝试从灰度 PNG 图像更改值,然后从这些更改的值创建图像。

The first step I took was using a python implementation of libpng .我采取的第一步是使用libpng 的 python 实现 With that I was able to get a list of all the pixel values of the PNG.有了它,我就能够获得 PNG 的所有像素值的列表。 It is a gray scale image so the values where from 0 to 100. I do a quick algorithm to change the values.这是一个灰度图像,所以值从 0 到 100。我做了一个快速算法来改变这些值。 And then I try to create it into a new PNG file.然后我尝试将它创建为一个新的 PNG 文件。 Its all on a single line so I use regex to format it into a 2D array.它全部在一行上,所以我使用正则表达式将其格式化为二维数组。

I attempted to use this that I found here我试图使用我在这里找到的这个

from PIL import Image
import numpy as np


pixels = [[100,0,0],[0,100,0],[0,0,100]]
# Convert the pixels into an array using numpy
array = np.array(pixels)

print(array)

# Use PIL to create an image from the new array of pixels
new_image = Image.fromarray(array, 'L')
new_image.save('testing.png')

But I guess the formatting that PIL uses is different from what the libpng is so instead of making an image that looks like 3 white pixels diagonally, I only get 1 white pixel on the top left.但我猜 PIL 使用的格式与 libpng 的格式不同,所以我没有制作对角线看起来像 3 个白色像素的图像,我只在左上角得到 1 个白色像素。 So either I change the values I am getting from libpng so that numpy works, or I find something in libpng that will allow me to change the values directly and create the new file.因此,要么我更改从 libpng 获得的值,以便 numpy 工作,要么我在 libpng 中找到一些允许我直接更改值并创建新文件的东西。

The error in your code is that you are not setting the right data type for the array.您的代码中的错误是您没有为数组设置正确的数据类型。 If you call array = np.array(pixels, dtype='uint8') then your code will work.如果您调用array = np.array(pixels, dtype='uint8')那么您的代码将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM