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;
JavaScript
x
25
25
1
import cv2
2
3
image=cv2.imread(r"C:UsersfazilDesktopc.png")
4
cv2.imshow("input",image)
5
cv2.cvtColor(image,cv2.CV_8U)
6
# kernel=np.array([
7
# [1,1,1],
8
# [1,1,1],
9
# [1,1,1]
10
# ],np.float32)
11
# image=cv2.filter2D(image,-1,kernel)
12
def blur(image):
13
height,width,channel=image.shape
14
result=np.zeros(image.shape,image.dtype)
15
for j in range(1,height-1):
16
for i in range(1,width-1):
17
for a in range(channel):
18
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)
19
return result
20
21
cv2.imshow("output",blur(image))
22
cv2.imwrite(r"C:UsersfazilDesktopoutput.png",image)
23
cv2.waitKey()
24
cv2.destroyAllWindows() ```
25
Advertisement
Answer
The following two methods work for me in Python OpenCV
Input:
JavaScript
1
34
34
1
import cv2
2
import numpy as np
3
4
image=cv2.imread("barn.jpg")
5
image=image.astype(np.float32)/255
6
#cv2.cvtColor(image,cv2.CV_8U)
7
kernel=np.array([
8
[1,1,1],
9
[1,1,1],
10
[1,1,1]
11
],np.float32)
12
outimage1=cv2.filter2D(image,cv2.CV_32F,kernel)/9
13
outimage1=(255*outimage1).clip(0,255).astype(np.uint8)
14
15
def blur(image):
16
height,width,channel=image.shape
17
result=np.zeros(image.shape,dtype=np.float32)
18
for j in range(1,height-1):
19
for i in range(1,width-1):
20
for a in range(channel):
21
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)
22
return result
23
24
outimage2 = blur(image)
25
outimage2 = outimage2.clip(0,255).astype(np.uint8)
26
27
cv2.imshow("input",image)
28
cv2.imshow("output1",outimage1)
29
cv2.imshow("output2",outimage2)
30
cv2.imwrite("barn_blur1.jpg",outimage1)
31
cv2.imwrite("barn_blur2.jpg",outimage2)
32
cv2.waitKey()
33
cv2.destroyAllWindows()
34
Blur Method 1:
Blur Method 2: