从数组生成Python像素图像

2024-09-30 16:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出不同的方法来可视化数据,以及如何掌握图像处理。在

Python 2.6: Creating image from array似乎在做一些不同的事情

我想举个简单的例子,我可以从头开始创建一个像素强度不同的图像。我使用A_pixelIntensity数组来声明像素颜色的强度。然后我在create_pixel_gradient函数中做一个转换,使高亮度像素更暗,低亮度像素更白。在

如何查看此图像?matplotlib.pyplot是最好的方法吗?那PIL.Image和{}呢?在

import numpy as np
#Intensity of Image
A_pixelIntensity = np.asarray([[1,1,1,1,1],[1,2,2,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,1,1,1,1]])
# [[1 1 1 1 1]
#  [1 2 2 2 1]
#  [1 2 3 2 1]
#  [1 2 2 2 1]
#  [1 1 1 1 1]]

#Color of Image
def create_pixel_gradient(A_intensity):
    maximum = np.amax(A_intensity)
    init = np.zeros(A_intensity.shape,dtype=tuple) #Create empty array to populate
    for i in range(A_intensity.shape[0]):
        for j in range(A_intensity.shape[1]):
            pixel_intensity = A_intensity[i,j] #Get original pixel intensities
            value = 255 - int(pixel_intensity*(255/np.amax(A_intensity))) #Lower intensities are more white (creates a gradient)
            init[i,j] = (value,255,value) #Populate array with RGB values
    return(init)

create_pixel_gradient(A_pixelIntensity)
# array([[(170, 255, 170), (170, 255, 170), (170, 255, 170), (170, 255, 170),
#         (170, 255, 170)],
#        [(170, 255, 170), (85, 255, 85), (85, 255, 85), (85, 255, 85),
#         (170, 255, 170)],
#        [(170, 255, 170), (85, 255, 85), (0, 255, 0), (85, 255, 85),
#         (170, 255, 170)],
#        [(170, 255, 170), (85, 255, 85), (85, 255, 85), (85, 255, 85),
#         (170, 255, 170)],
#        [(170, 255, 170), (170, 255, 170), (170, 255, 170), (170, 255, 170),
#         (170, 255, 170)]], dtype=object)  

Tags: 方法图像imageinitvaluecreatenp像素