在python中显示像素数组中的图像时出错
我有一个(numpy)像素阵列,如下所示:在python中显示像素数组中的图像时出错,python,python-3.x,image-processing,Python,Python 3.x,Image Processing,我有一个(numpy)像素阵列,如下所示: ''' import numpy and matplotlib ''' image = Image.open('trollface.png', 'r') width, height = image.size pixel_values = list(image.getdata()) pixel_values = np.array(pixel_values).reshape((width, height, 3)) # 3 channels RGB #h
''' import numpy and matplotlib '''
image = Image.open('trollface.png', 'r')
width, height = image.size
pixel_values = list(image.getdata())
pixel_values = np.array(pixel_values).reshape((width, height, 3)) # 3 channels RGB
#height, width = len(pixel_values), len(pixel_values[0])
我需要计算这个图像的数字负片-
for y in range(0,height):
for x in range(0,width):
R,G,B = pixel_values[x,y]
pixel_values[x,y] =(255 - R, 255 - G, 255 - B)
尝试在的帮助下显示以上像素的图像
但它只显示一个空白(白色)窗口,在CLI中:这里的目的是实现图像的负变换 像素转换可以使用
Image.point
方法直接应用于R、G、B波段
image = Image.open('trollface.png')
source = image.split()
r, g, b, a = 0, 1, 2, 3
negate = lambda i: 255 - i
transform = [source[band].point(negate) for band in (r, g, b)]
if len(source) == 4: # should have 4 bands for images with alpha channel
transform.append(source[a]) # add alpha channel
out = Image.merge(im.mode, transform)
out.save('negativetrollface.png')
编辑使用OP的程序,您有:
im = Image.open('trollface.png')
w, h = im.size
arr = np.array(im)
original_shape = arr.shape
arr_to_dim = arr.reshape((w, h, 4))
# Note that this is expensive.
# Always take advantage of array manipulation implemented in the C bindings
for x in range(0, w):
for y in range(0, h):
r, g, b, a = arr_to_dim[x, y]
arr_to_dim[x, y] = np.array([255 - r, 255 - g, 255 - b, a])
dim_to_arr = arr_to_dim.reshape(original_shape)
im = Image.fromarray(dim_to_arr)
out.save('negativetrollface.png')
错误消息似乎是不言自明的。重塑阵列的大小必须与原始阵列的大小相同。
width
和height
的值是多少?假设这是一幅210×210像素的图像,我真的很抱歉输入错误,我实际上试图将图像映射到相同的宽度和高度,但无法。您可能必须提供一个。感谢您的建议,但如果你能帮我找出我的错误,我将不胜感激。你需要将ndim 2阵列重塑为ndim 3。您要查找的是。重塑((宽度,高度,4))
尝试设置4而不是3显示新错误:plt.imshow(np.array(像素值)。重塑((宽度,高度,4)))值错误:新数组的总大小必须保持不变请参见编辑。我成功地运行了这个程序。这很有效[当我将w,h,3改为4时(没有alpha)]!在此上下文中实现c绑定是什么意思?
im = Image.open('trollface.png')
w, h = im.size
arr = np.array(im)
original_shape = arr.shape
arr_to_dim = arr.reshape((w, h, 4))
# Note that this is expensive.
# Always take advantage of array manipulation implemented in the C bindings
for x in range(0, w):
for y in range(0, h):
r, g, b, a = arr_to_dim[x, y]
arr_to_dim[x, y] = np.array([255 - r, 255 - g, 255 - b, a])
dim_to_arr = arr_to_dim.reshape(original_shape)
im = Image.fromarray(dim_to_arr)
out.save('negativetrollface.png')