无法将数组正确转换为图像

2024-04-26 00:56:02 发布

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

我想从文件中读取一个图像,将其调整为正方形尺寸(resize),然后将数组转换为图像来显示它。所以我为它写了下面的代码,但不幸的是fromarray方法最终没有显示真实的图像..我如何修复它?(我不想使用opencv或其他内置函数)

#import the libraries
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2
from PIL import Image
from scipy.misc import toimage

#reading the image
myimage = cv2.imread('mahdi.png')

#plotting the image
cv2.imshow('mahdi',myimage)
cv2.waitKey(0)
cv2.destroyAllWindows()

#save
cv2.imwrite('newmahdi.png',myimage)

#get size of image
dimensions = myimage.shape
height = myimage.shape[0]
width = myimage.shape[1]
print('Image Dimension    : ',dimensions)
print('Image Height       : ',height)
print('Image Width        : ',width,'\n')

#read image and convert to array
myimage1=mpimg.imread('mahdi.png')
imtopix = np.array(myimage1)
print('image to matrix:','\n',imtopix)

#resize image without OPENCV function... use numpy instead
myimage2 =np.resize(imtopix,(200,200))
newimg = Image.fromarray(myimage2)
newimg.save('my.png')
newimg.show()

Tags: the图像imageimportpngasnpcv2
1条回答
网友
1楼 · 发布于 2024-04-26 00:56:02

Numpy的resize()并不像你想象的那样。它不会沿阵列的轴对阵列进行重采样。你知道吗

假设源数组如下所示:

array([
        [11, 12, 13, 14, 15],
        [21, 22, 23, 24, 25]
      ])

a = np.resize(a, (3, 3))之后,结果如下所示:

array([
        [11, 12, 13],
        [14, 15, 21],
        [22, 23, 24]
      ])

如您所见,原始的第一行运行到第二行,以此类推,而最后一个像素只是消失了。这是因为np.resize()实际上并没有改变任何数据。它只是为内存中存在的数据分配了一个不同的形状,而原始行之间保持连续的顺序(如果使用Fortran样式的数组,则为列)。你知道吗

你真正想要的是枕头的^{}

newimg = Image.fromarray(imtopix)
newimg = newimg.resize((200, 200), resample=Image.BILINEAR)

选择任何适合您的用例的重采样方法。你知道吗

相关问题 更多 >