简体   繁体   中英

Convolve an image several times using for loop opencv python

below is a python code that performs convolution 10 times to an image

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. ( i'm new to python) I know this must be easy, however i just can't think out of the box

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

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. Without feeding the output back as the next input, you would be doing just a single convolution. And you'd be doing it 10x slower, uselessly computing identical result another nine times, discarding (over-writing) that work each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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