简体   繁体   English

使用 for 循环对图像进行多次卷积 opencv python

[英]Convolve an image several times using for loop opencv python

below is a python code that performs convolution 10 times to an image下面是对图像执行 10 次卷积的 python 代码

import cv2
import numpy as np
from skimage.exposure import rescale_intensity
kernel = np.ones((5,5),np.float32)/25
img = cv2.imread(r"C:/Users/engjb/.spyder-py3/examples/1.jpeg")





opencvOutput1 = cv2.filter2D(img, -1, kernel)


opencvOutput2 = cv2.filter2D(opencvOutput1, -1, kernel)
opencvOutput3 = cv2.filter2D(opencvOutput2, -1, kernel)
opencvOutput4 = cv2.filter2D(opencvOutput3, -1, kernel)
opencvOutput5 = cv2.filter2D(opencvOutput4, -1, kernel)
opencvOutput6 = cv2.filter2D(opencvOutput5, -1, kernel)
opencvOutput7 = cv2.filter2D(opencvOutput6, -1, kernel)
opencvOutput8 = cv2.filter2D(opencvOutput7, -1, kernel)
opencvOutput9 = cv2.filter2D(opencvOutput8, -1, kernel)
opencvOutput10 = cv2.filter2D(opencvOutput9, -1, kernel)

cv2.imshow("res",opencvOutput10)

cv2.waitKey(0)

cv2.destroyAllWindows()

How can i do this using one single for loop.我如何使用一个 for 循环来做到这一点。 ( i'm new to python) I know this must be easy, however i just can't think out of the box (我是 python 新手)我知道这一定很容易,但我就是不能开箱即用

My concept code:我的概念代码:

for i in rage(0,11):
 output = cv2.filter2D(img, -1, kernel)

However, this performs the convolution on the same source image in each iteration while i want the convolution to be performed on the output of each iteration但是,这在每次迭代中对同一源图像执行卷积,而我希望在每次迭代的 output 上执行卷积

img = cv2.imread( ... )
for i in range(10):
    print(i)
    img = cv2.filter2D(img, -1, kernel)

Notice that is quite different from assigning请注意,这与分配完全不同

    output = cv2.filter2D(img, ... )

since we want the next iteration to use the output.因为我们希望一次迭代使用 output。 Without feeding the output back as the next input, you would be doing just a single convolution.如果不将 output 作为下一个输入返回,您将只进行一次卷积。 And you'd be doing it 10x slower, uselessly computing identical result another nine times, discarding (over-writing) that work each time.而且你会做它慢 10 倍,无用地计算相同的结果另外 9 次,丢弃(覆盖)每次都有效。

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

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