首页 > 解决方案 > 图像处理的随机采样

问题描述

任何人都可以帮助提供此代码吗?我想通过使用随机采样来减小图像大小,但无法弄清楚如何设置输入补丁的限制。

# New smaller image
img_small = np.zeros((img.shape[0] // factor, img.shape[1] // factor),
                     dtype=np.int64)   

# Loop over the rows of the smaller image
for i in range(img_small.shape[0]):
    # Loop over the columns of the smaller image
    for j in range(img_small.shape[1]):
        # The input patch should consist of rows from factor * i to
        # factor * (i + 1) - 1, and columns from factor * j to
        # factor * (j + 1) - 1

        # input_patch = img[  # Extract the input patch

        # Can use np.random.choice(input_patch.flatten(), ...) to choose random
        # pixels from input_patch 

        # img_small[i, j] =  # Set the output pixel
            img_small[i, j] = 

标签: pythonimage-processing

解决方案


限制在评论中给出,只需将它们应用于数组。使用示例图像 在此处输入图像描述

并使用您的代码(添加图像加载并将其转换为灰度 - 如果需要颜色,您将需要添加颜色处理):

from PIL import Image
import numpy as np
from matplotlib.pyplot import imshow

# load the image and convert to greyscale
image = Image.open('imglrg0.jpg').convert('LA')
# convert image to numpy array
img_lrg = np.asarray(image)
#imshow(img_lrg)

factor = 8

# New smaller image
img_small = np.zeros((img_lrg.shape[0] // factor, img_lrg.shape[1] // factor),
                     dtype=np.int64)   

# Loop over the rows of the smaller image
for i in range(img_small.shape[0]):
    # Loop over the columns of the smaller image
    for j in range(img_small.shape[1]):
        # The input patch should consist of rows from factor * i to
        # factor * (i + 1) - 1, and columns from factor * j to
        # factor * (j + 1) - 1

        # input_patch = img[  # Extract the input patch
        input_patch = img_lrg[i * factor:(i+1) * factor - 1, j * factor:(j+1) * factor - 1]

        # Can use np.random.choice(input_patch.flatten(), ...) to choose random
        # pixels from input_patch

        # img_small[i, j] =  # Set the output pixel
        img_small[i, j] = np.random.choice(input_patch.flatten())

imshow(np.asarray(img_small))

这导致(对于factor=8. 不是最好的结果,但可以识别。也许可以稍微改进一下采样。我只是使用 matplotlib 来快速显示结果,所以它的颜色变淡了。):

在此处输入图像描述

就像对抽样的补充:像这样选择三个点的平均值会img_small[i, j] = np.average(np.random.choice(input_patch.flatten(), 3))导致实质性的改进: 在此处输入图像描述


推荐阅读