Slide a window through an image, and change the value of center pixel in window based on the average value of the sliding window
I am trying to slide a 5 by 5
2D window across a gray image.
If all the pixels within that 2D window equal to 200, replace the center pixel value within the window with 100.
import cv2
import numpy as np
from PIL import Image
from scipy.signal import convolve2d as conv2
image = cv2.imread("testImage.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
output = (conv2(gray, np.ones((5, 5), dtype=int), 'valid') == 200).astype(int)
I am not sure where to go from here or how to do this
Solution 1:
You have it almost correct. The output of your convolve2d thing is a boolean array that has True where you want the value changed. You can use that as a fancy index into the original array, one of numpy's best features. Note that you need "same", not "valid", to make sure the output array had the right size.
import cv2
import numpy as np
from scipy.signal import convolve2d as conv2
image = cv2.imread("splat.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
box = np.ones((3,3),dtype=int)
output = conv2(gray, box, 'same') == 200
gray[output] = 100