Home > Mobile >  How do I return an array of pixel values using kernel to condense them (blur)? *Python*
How do I return an array of pixel values using kernel to condense them (blur)? *Python*

Time:11-17

So, what I'm trying to do is take an image (let's say 100x100) and do a 5x5 kernel over the image:

kernel = np.ones((5, 5), np.float32)/25

and then output an array for each iteration of the kernel (like in cv2.filter2D) like:

kernel_vals.append(np.array([[indexOfKernelIteration], [newArrayOfEditedKernelValues]]))

What I'm missing is how to get it to iterate across the image and output the pixel values of the new "image" that would be produced by:

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

I just want, for each kernel, the output that is displayed on the new image to be put into the "kernel_vals" array.

image

^NOT INTO AN IMAGE

Attached image for visual reference.

CodePudding user response:

imread returns an np.array, so if i understand what you want to do, you have the solution in the question. For completeness sake, see the code below.

import cv2

img = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE)
print(type(img))
print(img[:10, :10])

kernel = np.ones((5, 5), np.float32)/25
kernel_vals = cv2.filter2D(img, -1, kernel)
print(kernel_vals[:10, :10])

And the output is (with added newlines for readability)

<class 'numpy.ndarray'>

[[255 255 255 255 255 255 255 255 255 255]
 [255 255 255 255 255 255 255 255 255 255]
 [255 255 255 255 255 255 255 255 255 255]
 [255 255 255   0 255 255 255   0 255 255]
 [255 255 255   0 255 255 255   0 255 255]
 [255 255 255   0 255 255 255   0 255 255]
 [255 255 255   0 255 255 255   0 255 255]
 [255 255 255   0 255 255 255   0 255 255]
 [255 255 255   0 255 255 255   0 255 255]
 [255 255 255   0 255 255 255   0 255 255]]

[[255 255 255 255 255 255 255 255 255 255]
 [255 245 245 245 245 235 245 245 245 235]
 [255 235 235 235 235 214 235 235 235 214]
 [255 224 224 224 224 194 224 224 224 194]
 [255 214 214 214 214 173 214 214 214 173]
 [255 204 204 204 204 153 204 204 204 153]
 [255 204 204 204 204 153 204 204 204 153]
 [255 204 204 204 204 153 204 204 204 153]
 [255 204 204 204 204 153 204 204 204 153]
 [255 204 204 204 204 153 204 204 204 153]]

Now, since kernel_vals is an np.array, you can flatten it, turn it into a list, or manipulate it in any other way you want

  • Related