前幾天,老師布置了這樣一個任務,讀取圖片並顯示,反色后進行顯示;進行Sobel算子濾波,然后反色,進行顯示;進行Robers算子濾波,然后反色,進行顯示。我最后加上了Laplace算子濾波,進行了比較。下面我來講一下我的實現方法:
一、實現過程
思路:先完成每種函數的算法,接下來是反色函數,最后實現。
import cv2
import numpy as np
# robert 算子[[-1,-1],[1,1]]
def robert_suanzi(img):
r, c = img.shape
r_sunnzi = [[-1,-1],[1,1]]
for x in range(r):
for y in range(c):
if (y + 2 <= c) and (x + 2 <= r):
imgChild = img[x:x+2, y:y+2]
list_robert = r_sunnzi*imgChild
img[x, y] = abs(list_robert.sum()) # 求和加絕對值
return img
# # sobel算子的實現
def sobel_suanzi(img):
r, c = img.shape
new_image = np.zeros((r, c))
new_imageX = np.zeros(img.shape)
new_imageY = np.zeros(img.shape)
s_suanziX = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) # X方向
s_suanziY = np.array([[-1,-2,-1],[0,0,0],[1,2,1]])
for i in range(r-2):
for j in range(c-2):
new_imageX[i+1, j+1] = abs(np.sum(img[i:i+3, j:j+3] * s_suanziX))
new_imageY[i+1, j+1] = abs(np.sum(img[i:i+3, j:j+3] * s_suanziY))
new_image[i+1, j+1] = (new_imageX[i+1, j+1]*new_imageX[i+1,j+1] + new_imageY[i+1, j+1]*new_imageY[i+1,j+1])**0.5
# return np.uint8(new_imageX)
# return np.uint8(new_imageY)
return np.uint8(new_image) # 無方向算子處理的圖像
# Laplace算子
# 常用的Laplace算子模板 [[0,1,0],[1,-4,1],[0,1,0]] [[1,1,1],[1,-8,1],[1,1,1]]
def Laplace_suanzi(img):
r, c = img.shape
new_image = np.zeros((r, c))
L_sunnzi = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]])
# L_sunnzi = np.array([[1,1,1],[1,-8,1],[1,1,1]])
for i in range(r-2):
for j in range(c-2):
new_image[i+1, j+1] = abs(np.sum(img[i:i+3, j:j+3] * L_sunnzi))
return np.uint8(new_image)
#反色函數
def inverse_color(img):
height,width = img.shape
img2 = img.copy()
for i in range(height):
for j in range(width):
img2[i,j] = (255-img[i,j])
return img2
img = cv2.imread('E:/test3.bmp', cv2.IMREAD_GRAYSCALE)
cv2.imshow('image', img)
img2 = inverse_color(img)
cv2.imshow('image2',img2)
# # robers算子
out_robert = robert_suanzi(img)
out_robert = inverse_color(out_robert)
cv2.imshow('robert_image', out_robert)
# sobel 算子
out_sobel = sobel_suanzi(img)
out_sobel = inverse_color(out_sobel)
cv2.imshow('sobel_image', out_sobel)
# Laplace算子
out_laplace = Laplace_suanzi(img)
out_laplace = inverse_color(out_laplace)
cv2.imshow('laplace_image', out_laplace)
cv2.waitKey(0)
cv2.destroyAllWindows()
二、運行效果
原圖
反色后
Sobel算子濾波
robert算子濾波
laplace算子濾波
三、問題及解決辦法
1.出現找不到文件的情況
這是第一次實驗就遇到的問題,我以為還是符號的問題(就是文件前面要用/),但發現改了之后仍然出現問題,然后發現是我把圖片的后綴記錯了,如下圖,test3的后綴是bmp,而我代碼里出了問題,后來改正了就可以了。
2.運行結果沒有進行反色處理。
解決方法:其實就是忘記了題目的要求,然后后來加上了反色的代碼,結果就是題目要求的了。代碼如下: