Python,Numpy,OpenCV - 创建一个修改过的(同样快速的)“addWeighted”功能 [英] Python, Numpy, OpenCV -- Creating a modified (and equally fast) "addWeighted" function

查看:554
本文介绍了Python,Numpy,OpenCV - 创建一个修改过的(同样快速的)“addWeighted”功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python中的一个程序,它使用的函数非常类似于openCV中的 addWeighted 函数。不同之处在于它实际上并没有添加代表图像的numpy数组,而是在任何特定坐标处使用哪个像素更亮并使用该值。

I am working on a program in python that makes use of a function very similar to the addWeighted function in openCV. The difference is that it doesn't actually add the numpy arrays representing the images, instead, it takes whichever pixel is brighter at any particular coordinate and uses that value.

什么然而,我发现,尽管这些函数的功能非常相似,但 addWeighted 函数要快得多。所以我的问题是,如何修改我当前的解决方案同样快?有没有办法可以使用多处理模块或类似的东西?

What I have been finding, however, is that despite the fact that these functions do very similar things, the addWeighted function is much faster. So my question is, how can I modify my current solution to be equally as fast? Is there a way I can use the multiprocessing module, or something similar?

以下是代码:

image = np.zeros(image_1.shape)
for row_index, row in enumerate(image_1):
     for col_index, col in enumerate(row):
          pixel_1 = image_1[row_index, col_index]
          pixel_2 = image_2[row_index, col_index]
          sum_1 = int(pixel_1[0]) + int(pixel_1[1]) + int(pixel_1[2])
          sum_2 = int(pixel_2[0]) + int(pixel_2[1]) + int(pixel_2[2])

          if sum_2 > sum_1:
               image[row_index, col_index] = pixel_2
          else:
               image[row_index, col_index] = pixel_1

其中 image_1 image_2 都是代表图像的numpy数组,两者都是相同的形状(720,1280,3)

Where image_1 and image_2 are both numpy arrays representing images, both with the same shape (720, 1280, 3).

推荐答案

一个向量化方法将是 -

One vectorized approach would be -

mask = image_2.astype(int).sum(-1) > image_1.astype(int).sum(-1)
out = np.where(mask[...,None], image_2, image_1)

步骤:


  • 转换为 int dtypes,沿最后一个轴求和并执行逐元素比较。这会给我们一个面具。

  • Convert to int dtypes, sum along the last axis and perform element-wise comparisons. This would give us a mask.

使用 np.where 使用此掩码,扩展为相同没有。作为输入数组的dims进行选择。这采用了 NumPy广播 以矢量化方式进行选择。所以,值得一看。

Use np.where with this mask, extended to the same no. of dims as input arrays to do the choosing. This employs the concept of NumPy broadcasting to do the choosing in a vectorized manner. So, that's worth a good look.

注意:或者,我们也可以使用 keepdims = True 保持不行。求和时的暗淡,从而避免在下一步中延长暗淡。

Note: Alternatively, we can also use keepdims=True to keep the no. of dims while summing and thus avoid extending dims in the next step.

这篇关于Python,Numpy,OpenCV - 创建一个修改过的(同样快速的)“addWeighted”功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆