Skip to content
Advertisement

Filter in opencv/python

I am trying to learn filters in opencv and running this code. But the problem is that when ı run the code it gives me an almost dark image and warns me with “c:/Users/fazil/Desktop/Yeni Metin Belgesi (3).py:19: RuntimeWarning: overflow encountered in ubyte_scalars result[j,i,a]=int((image[j,i,a]+image[j,i-1,a]+image[j,i+1,a]+image[j+1,i,a]+image[j-1,i,a]+image[j+1,i+1,a]+image[j+1,i-1,a]+image[j-1,i-1,a]+image[j-1,i+1,a])/9)”. And if ı comment these out and run code with the lines working with cv2.filter2d method it gives me an almost whiite image. I mean, doesnt they have to do the same thing, and musnt that filter blur the image? Here’s my code;

import cv2

image=cv2.imread(r"C:UsersfazilDesktopc.png")
cv2.imshow("input",image)
cv2.cvtColor(image,cv2.CV_8U)
# kernel=np.array([
#     [1,1,1],
#     [1,1,1],
#     [1,1,1]
# ],np.float32)
# image=cv2.filter2D(image,-1,kernel)
def blur(image):
    height,width,channel=image.shape
    result=np.zeros(image.shape,image.dtype)
    for j in range(1,height-1):
        for i in range(1,width-1):
            for a in range(channel):
                result[j,i,a]=int((image[j,i,a]+image[j,i-1,a]+image[j,i+1,a]+image[j+1,i,a]+image[j-1,i,a]+image[j+1,i+1,a]+image[j+1,i-1,a]+image[j-1,i-1,a]+image[j-1,i+1,a])/9)
    return result

cv2.imshow("output",blur(image))
cv2.imwrite(r"C:UsersfazilDesktopoutput.png",image)
cv2.waitKey()
cv2.destroyAllWindows()  ```

Advertisement

Answer

The following two methods work for me in Python OpenCV

Input:

enter image description here

import cv2
import numpy as np

image=cv2.imread("barn.jpg")
image=image.astype(np.float32)/255
#cv2.cvtColor(image,cv2.CV_8U)
kernel=np.array([
                [1,1,1],
                [1,1,1],
                [1,1,1]
                ],np.float32)
outimage1=cv2.filter2D(image,cv2.CV_32F,kernel)/9
outimage1=(255*outimage1).clip(0,255).astype(np.uint8)

def blur(image):
    height,width,channel=image.shape
    result=np.zeros(image.shape,dtype=np.float32)
    for j in range(1,height-1):
        for i in range(1,width-1):
            for a in range(channel):
                result[j,i,a]=(255*(image[j-1,i-1,a]+image[j-1,i,a]+image[j-1,i+1,a]+image[j,i-1,a]+image[j,i,a]+image[j,i+1,a]+image[j+1,i-1,a]+image[j+1,i,a]+image[j+1,i+1,a])/9)
    return result

outimage2 = blur(image)
outimage2 = outimage2.clip(0,255).astype(np.uint8)

cv2.imshow("input",image)
cv2.imshow("output1",outimage1)
cv2.imshow("output2",outimage2)
cv2.imwrite("barn_blur1.jpg",outimage1)
cv2.imwrite("barn_blur2.jpg",outimage2)
cv2.waitKey()
cv2.destroyAllWindows()

Blur Method 1:

enter image description here

Blur Method 2:

enter image description here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement