Numpy调整图像大小

2024-09-25 00:26:35 发布

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

我想拍摄一张图像,改变图像的比例,而它是一个numpy数组。 我想使用本机NumPy函数,不带PIL、cv2、SciPy等

现在我有这个:

from copy import copy
import numpy as np
from scipy import misc


img = misc.face()  # racoon from SciPy(np.ndarray)
img2 = copy(img)  # copy of racoon, because misc.face() is Descriptor(?)
img2.shape()  # (768, 1024, 3)

我需要的形状=(30724096,3)

我可以很容易地用枕头

CONVERT_IMAGE = Image.fromarray(img.astype('uint8'), 'RGB')
CONVERT_IMAGE = CONVERT_IMAGE.resize((4096, 3072), Image.NEAREST)

IMAGE_AS_ARRAY = np.asarray(CONVERT_IMAGE)
IMAGE_AS_ARRAY.shape  # 3072 4096 3

但是我真的需要只使用NumPy函数,而不使用其他lib

你能帮我吗?我在NumPy和3D阵列方面真的很弱


Tags: 函数from图像imageimportnumpyconvertimg
1条回答
网友
1楼 · 发布于 2024-09-25 00:26:35

仅限于使用某些缩放因子n进行整整数上缩放,并且不使用实际插值,您可以使用^{}两次来获得所述结果:

import numpy as np

# Original image with shape (4, 3, 3)
img = np.random.randint(0, 255, (4, 3, 3), dtype=np.uint8)

# Scaling factor for whole integer upscaling
n = 4

# Actual upscaling (results to some image with shape (16, 12, 3)
img_up = np.repeat(np.repeat(img, n, axis=0), n, axis=1)

# Outputs
print(img[:, :, 1], '\n')
print(img_up[:, :, 1])

以下是一些输出:

[[148 242 171]
 [247  40 152]
 [151 131 198]
 [ 23 185 144]] 

[[148 148 148 148 242 242 242 242 171 171 171 171]
 [148 148 148 148 242 242 242 242 171 171 171 171]
 [148 148 148 148 242 242 242 242 171 171 171 171]
 [148 148 148 148 242 242 242 242 171 171 171 171]
 [247 247 247 247  40  40  40  40 152 152 152 152]
 [247 247 247 247  40  40  40  40 152 152 152 152]
 [247 247 247 247  40  40  40  40 152 152 152 152]
 [247 247 247 247  40  40  40  40 152 152 152 152]
 [151 151 151 151 131 131 131 131 198 198 198 198]
 [151 151 151 151 131 131 131 131 198 198 198 198]
 [151 151 151 151 131 131 131 131 198 198 198 198]
 [151 151 151 151 131 131 131 131 198 198 198 198]
 [ 23  23  23  23 185 185 185 185 144 144 144 144]
 [ 23  23  23  23 185 185 185 185 144 144 144 144]
 [ 23  23  23  23 185 185 185 185 144 144 144 144]
 [ 23  23  23  23 185 185 185 185 144 144 144 144]]
                    
System information
                    
Platform:     Windows-10-10.0.16299-SP0
Python:       3.8.5
NumPy:        1.19.2
                    

相关问题 更多 >