Filter in opencv/python

♀尐吖头ヾ 提交于 2020-12-15 06:29:07

问题


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:\Users\fazil\Desktop\c.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:\Users\fazil\Desktop\output.png",image)
cv2.waitKey()
cv2.destroyAllWindows()  ```

回答1:


The following two methods work for me in Python OpenCV

Input:

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:

Blur Method 2:



来源:https://stackoverflow.com/questions/64763938/filter-in-opencv-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!