python - 图像处理的随机采样
问题描述
任何人都可以帮助提供此代码吗?我想通过使用随机采样来减小图像大小,但无法弄清楚如何设置输入补丁的限制。
# 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] =
解决方案
并使用您的代码(添加图像加载并将其转换为灰度 - 如果需要颜色,您将需要添加颜色处理):
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))
导致实质性的改进:
推荐阅读
- templates - 如何仅为标题列更改内部边框的颜色?
- angular - 无法使用 ngModel 和模型对象填充角度形式
- r - 缩放 SQL 地理多边形
- sass - 伪元素 ::after 和 ::before 在 Foundation 中不起作用有什么原因吗?
- c++ - std::generate_n 的并行执行可变 lambda 生成器
- r - 使用 for 循环在 R 中重新安排 GLM 分析的数据
- angular - Chart.js 不会在我的 Ionic 4 / Angular 应用程序中调用 plugins.datalabels.formatter()
- java - 如何从服务器响应中提取适配器 RecyclerView 的对象列表?
- facebook-ads-api - Facebook 受众网络问题
- java - java中需要String.hashCode()方法的证明/分解