我用以下方式创建了一个NumPy数组:
data = numpy.zeros((1, 15, 3), dtype = numpy.uint8)
然后我用RGB像素值填充这个数组,产生一个小的彩色图像,可以使用如下过程保存:
image = Image.fromarray(data)
image.save("image.png")
为了创建600 x 300像素的图像,我怎么能缩放NumPy数组的大小(没有插值)?
答案 0 :(得分:6)
您可以按照评论中的建议使用numpy.kron,也可以使用以下选项
1]使用 PILLOW 维持宽高比
如果您想保持图片的宽高比,那么您可以使用thumbnail()
方法
from PIL import Image
def scale_image(input_image_path,
output_image_path,
width=None,
height=None):
original_image = Image.open(input_image_path)
w, h = original_image.size
print('The original image size is {wide} wide x {height} '
'high'.format(wide=w, height=h))
if width and height:
max_size = (width, height)
elif width:
max_size = (width, h)
elif height:
max_size = (w, height)
else:
# No width or height specified
raise RuntimeError('Width or height required!')
original_image.thumbnail(max_size, Image.ANTIALIAS)
original_image.save(output_image_path)
scaled_image = Image.open(output_image_path)
width, height = scaled_image.size
print('The scaled image size is {wide} wide x {height} '
'high'.format(wide=width, height=height))
if __name__ == '__main__':
scale_image(input_image_path='caterpillar.jpg',
output_image_path='caterpillar_scaled.jpg',
width=800)
我使用了Image.ANTIALIAS
标记,它会应用高质量的下采样过滤器,从而产生更好的图像
2]使用 OpenCV
OpenCV具有cv2.resize()
功能
import cv2
image = cv2.imread("image.jpg") # when reading the image the image original size is 150x150
print(image.shape)
scaled_image = cv2.resize(image, (24, 24)) # when scaling we scale original image to 24x24
print(scaled_image.shape)
输出
(150, 150)
(24, 24)
cv2.resize()
函数还有插值作为参数,您可以通过它指定调整图像大小的方式插入方法:
3]使用 PILLOW 库
使用Image.resize()
from PIL import Image
image = Image.open("image.jpg") # original image of size 150x150
resized_image = sourceimage.resize((24, 24), resample=NEAREST) # resized image of size 24x24
resized_image.show()
4]使用 SK-IMAGE 库
使用skimage.transform.resize()
from skimage import io
image = io.imread("image.jpg")
print(image.shape)
resized_image = skimage.transform.resize(image, (24, 24))
print(resized_image.shape)
输出
(150, 150)
(24, 24)
5]使用 SciPy
使用scipy.misc.imresize()
功能
import numpy as np
import scipy.misc
image = scipy.misc.imread("image.jpg")
print(image.shape)
resized_image = scipy.misc.imresize(x, (24, 24))
resized_image
print(resized_image.shape)
输出
(150, 150)
(24, 24)
答案 1 :(得分:2)
在scikit-image
中,我们有transform
from skimage import transform as tf
import matplotlib.pyplot as plt
import numpy as np
data = np.random.random((1, 15, 3))*255
data = data.astype(np.uint8)
new_data = tf.resize(data, (600, 300, 3), order=0) # order=0, Nearest-neighbor interpolation
f, (ax1, ax2, ax3) = plt.subplots(1,3, figsize=(10, 10))
ax1.imshow(data)
ax2.imshow(new_data)
ax3.imshow(tf.resize(data, (600, 300, 3), order=1))
答案 2 :(得分:0)
以下是使用PIL调整存储在numpy数组中的图像大小的代码段。在此示例中,list(range(0, 8))
是一个二维numpy数组。
img