通过平均值对Python中的numpy图像数组进行下采样



如何通过以numpy为单位对像素进行平均,将任何分辨率的图像降采样到四分之一大小?

我通过研究得出的结果只适用于方形图像(即512 X 512到128 X 128(,但不适用于不同尺寸的图像(即2400 X 1800到600 X 450(。在这些情况下,我得到一个IndexError:索引450超出了大小为450的轴1的界限。

我尝试在不安装其他包和库的情况下,使用numpy数组操作来执行此任务。

我研究了一个函数

numpy.mean()

但我不知道如何在这个问题上使用它。

import cv2
import numpy as np
def quarter_res_avg(im):
original_width = im.shape[1]
original_height = im.shape[0]
width = original_width / 4
height = original_height / 4
resized_image = np.zeros(shape=(width, height, 3), dtype=np.uint8)
scale = 4
for i in range(width):
for j in range(height):
temp = np.array([0, 0, 0])
for x in range(scale):
for y in range(scale):
temp += im[i*scale+x, j*scale+y]
resized_image[i, j] = temp/(scale*scale)
return resized_image
im = cv2.imread('Lenna_test_image.png', 1)
cv2.imwrite('Lenna_test_image_avg.png', quarter_res_avg(im))

任何想法都将不胜感激。

谢谢。

import numpy as np
import skimage.measure
your_array = np.random.rand(2400, 800)
new_array = skimage.measure.block_reduce(your_array, (4,4), np.mean)
print(new_array.shape)
Out[18]: (600, 450)

首先将M x N图像重塑为(M//4(x 4 x(N//4(x 4.数组,然后在第二个维度和最后一个维度中使用np.mean

from typing import Tuple
import numpy as np
def downsample_by_averaging(img: np.ndarray, window_shape: Tuple[int, int]) -> np.ndarray:
return np.mean(
img.reshape((
*img.shape[:-2],
img.shape[-2] // window_shape[-2], window_shape[-2],
img.shape[-1] // window_shape[-1], window_shape[-1],
)),
axis=(-1, -3),
)
downsample_by_averaging(img, (4, 4))

在@MarkSetchell的帮助下,我在问题评论中得到了答案。

不使用np.mean((

def quarter_res_avg(im):
original_width = im.shape[1]
original_height = im.shape[0]
width = original_width / 4
height = original_height / 4
resized_image = np.zeros(shape=(height, width, 3), dtype=np.uint8)
scale = 4
for i in range(height):
for j in range(width):
temp = np.array([0, 0, 0])
for x in range(scale):
for y in range(scale):
temp += im[i*scale + x, j*scale + y]
resized_image[i, j] = temp/(scale*scale)
return resized_image
im = cv2.imread('Lenna_test_image.png', 1)
cv2.imwrite('Lenna_test_image_resized.png', quarter_res_avg(im))    

使用np.mean((将for循环替换为:

for i in range(0, original_height, scale):
for j in range(0, original_width, scale):
resized_image[i/scale, j/scale] = np.mean(im[i:i + scale, j:j+scale], axis=(0,1))

最新更新