简体   繁体   English

Python / opencv:使图像像素为最接近的4像素的平均值

[英]Python / opencv: Make pixels of images be the average of nearest 4 pixels

I need to reduce the actual resolution of a picture so that each pixel in 4-pixel rectangle is the mean value of those 4 pixels. 我需要降低图片的实际分辨率,以使4像素矩形中的每个像素都是这4像素的平均值。

ie

p1 p2 p6 p7         a1 a1 a2 a2 
p3 p4 p8 p9  ... -> a1 a1 a2 a2 where a1 = average(p1, p2, p3, p4), a2 = average(p6, p7, p8, p9) etc

Is it possible to efficiently do that using python/opencv not manipulating individual pixels? 是否可以使用python / opencv有效地做到这一点,而不处理单个像素? Does bilinear/nearest neighbor rescaling down and back to the original resolution produce the requested result(not just the visual effect)? 双线性/最近邻居缩小比例并返回原始分辨率是否会产生所需的结果(而不仅仅是视觉效果)? The pictures are monochrome. 图片是单色的。

If you are interested in transparent numpy/indexing based solution try something like that: 如果您对基于透明numpy / indexing的透明解决方案感兴趣,请尝试以下操作:

I use some dummy data to test the solution: 我使用一些虚拟数据来测试解决方案:

img = np.array([range(0,4), range(4, 8), range(8, 12), range(12, 16)])

This gives us following 'image': 这给了我们以下“图像”:

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]

Then I create four subimages by taking every second element: 然后,我每隔两个元素创建四个子图像:

subimg1 = img[::2, ::2]
subimg2 = img[1::2, ::2]
subimg3 = img[::2, 1::2]
subimg4 = img[1::2, 1::2]

Now you can average the corresponding samples using numpy: 现在,您可以使用numpy对相应样本进行平均:

average = np.average([subimg1, subimg2, subimg3, subimg4], 0)

And create the output: 并创建输出:

output = np.zeros(img.shape)
output[::2, ::2] = average
output[1::2, ::2] = average
output[::2, 1::2] = average
output[1::2, 1::2] = average

And the output for given test data is: 给定测试数据的输出为:

[[  2.5   2.5   4.5   4.5]
 [  2.5   2.5   4.5   4.5]
 [ 10.5  10.5  12.5  12.5]
 [ 10.5  10.5  12.5  12.5]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM