【发布时间】:2018-01-27 16:47:08
【问题描述】:
我有一个小的二进制 numpy 数组 X
例如。
[[0,0,0,0,0],
[0,0,1,0,0],
[0,1,0,1,0],
[0,0,1,0,0],
[0,0,0,0,0]]
我使用
将其保存到图像中plt.imsave('file.png', X, cmap=cm.gray)
唯一的问题是图像在 5x5 分辨率下很小。如何提高图像的分辨率,同时仍保留图像中的信息?
【问题讨论】:
我有一个小的二进制 numpy 数组 X
例如。
[[0,0,0,0,0],
[0,0,1,0,0],
[0,1,0,1,0],
[0,0,1,0,0],
[0,0,0,0,0]]
我使用
将其保存到图像中plt.imsave('file.png', X, cmap=cm.gray)
唯一的问题是图像在 5x5 分辨率下很小。如何提高图像的分辨率,同时仍保留图像中的信息?
【问题讨论】:
您可以使用PyPNG 库。这个库可以很简单,比如
import png
png.from_array(X, 'L').save("file.png")
你也可以像下面这样使用scipy
import scipy.misc
scipy.misc.imsave('file.png', X)
【讨论】:
您可以使用Numpy 最大化您的数组的维度并分别增加每个索引周围的数量:
In [48]: w, h = a.shape
In [49]: new_w, new_h = w * 5, h * 5
In [50]: new = np.zeros((new_w, new_h))
In [51]: def cal_bounding_square(x, y, new_x, new_y):
x = x * 5
y = y * 5
return np.s_[max(0, x-5):min(new_x, x+5),max(0, y-5):min(new_y, y+5)]
....:
In [52]: one_indices = np.where(a)
In [53]: for i, j in zip(*one_indices):
slc = cal_bounding_square(i, j, new_w, new_h)
new[slc] = 1
....:
【讨论】:
具有更多像素的图像将包含更多信息,但像素可能是多余的。您可以制作一个更大的图像,其中每个矩形都是黑色或白色:
your_data = [[0,0,0,0,0],
[0,0,1,0,0],
[0,1,0,1,0],
[0,0,1,0,0],
[0,0,0,0,0]]
def enlarge(old_image, horizontal_resize_factor, vertical_resize_factor):
new_image = []
for old_row in old_image:
new_row = []
for column in old_row:
new_row += column*horizontal_resize_factor
new_image += [new_row]*vertical_resize_factor
return new_image
# Make a 7x7 rectangle of pixels for each of your 0 and 1s
new_image = enlarge(your_data, 7, 7)
【讨论】:
这个问题可以通过简单的 numpy hack 来解决。调整数组大小并用零填充。
将 X 视为您当前的 numpy 数组
X = np.array([[0,0,0,0,0],
[0,0,1,0,0],
[0,1,0,1,0],
[0,0,1,0,0],
[0,0,0,0,0]])
创建一个具有所需尺寸的新零数组
new_X = np.zeros((new_height,new_width))
将您的原始数组添加到其中
new_X[:X.shape[0], :X.shape[1]] = X
【讨论】: