1 # -*- coding: utf-8 -*- 2 """ 3 Created on Wed Mar 7 11:04:15 2018 4 5 @author: markli 6 """ 7 import numpy as np; 8 from PIL import Image; 9 import matplotlib.pyplot as pyplot; 10 class ImageFilter: 11 def __init__(self,filepath): 12 self.path = filepath; 13 14 def Filter(self,filtermatrix): 15 """步長設定為1""" 16 img = Image.open(self.path); 17 #img = img.resize((32,32)); 18 r,g,b = img.split(); #rgb 通道分離 19 #轉為數字矩陣 20 r_arr = np.array(r); 21 g_arr = np.array(g); 22 b_arr = np.array(b); 23 24 matrix = [r_arr,g_arr,b_arr]; 25 #過濾后的結果矩陣 26 fm = np.ones((r_arr.shape[0] - filtermatrix.shape[0] + 1,r_arr.shape[1] - filtermatrix.shape[1]+1)); 27 fm_rgb = []; 28 #卷積運算 實現過濾 29 for m in matrix: 30 row = 0; 31 for i in range(fm.shape[0]): 32 col = 0; 33 for j in range(fm.shape[1]): 34 temp = m[row:row + filtermatrix.shape[0],col:col + filtermatrix.shape[1]]; 35 fm[i][j] = np.sum(np.multiply(temp,filtermatrix)); 36 col = col + 1; 37 row = row + 1; 38 39 fm_rgb.append(fm); 40 41 return fm_rgb; 42 # #數字矩陣轉為RGB通道像素 43 # r = Image.fromarray(fm_rgb[0]).convert('L'); 44 # g = Image.fromarray(fm_rgb[1]).convert('L'); 45 # b = Image.fromarray(fm_rgb[2]).convert('L'); 46 # image = Image.merge("RGB", (r, g, b)); 47 # #圖片顯示 48 # pyplot.imshow(image); 49 # pyplot.show(); 50 def MergeEdage(self,savepath): 51 leftmatrix = np.array([[1,0,-1],[1,0,-1],[1,0,-1]]);#左邊界 52 left = self.Filter(leftmatrix); 53 rightmatrix = np.array([[-1,0,1],[-1,0,1],[-1,0,1]]);#右邊界 54 right = self.Filter(rightmatrix); 55 w_1,h_1 = left[0].shape; #left 和 right 維數相同,使用哪個都可以 56 full_edage = []; 57 for i in range(3): 58 m = np.hstack((left[i][:,:int(w_1/2)],right[i][:,w_1-int(w_1/2):])); 59 full_edage.append(m); 60 61 #數字矩陣轉為RGB通道像素 62 r = Image.fromarray(full_edage[0]).convert('L'); 63 g = Image.fromarray(full_edage[1]).convert('L'); 64 b = Image.fromarray(full_edage[2]).convert('L'); 65 image = Image.merge("RGB", (r, g, b)); 66 #圖片顯示 67 pyplot.imshow(image); 68 pyplot.show(); 69 image.save(savepath); 70 71 img = ImageFilter("C:\\Users\\yangp\\Desktop\\612474963277897033.jpg"); 72 img.MergeEdage("C:\\Users\\yangp\\Desktop\\fulledage.jpg"); 73
下面給出原圖、左邊界和右邊界識別情況:


最后是將左右邊界合並,形成整體:

最后說明一下,其中的過濾矩陣可以擴大,將過濾矩陣值的變化放慢,可以使圖像的識別更加細致,在這里本人的電腦配置太低,就不演示了。當然圖片的輪廓可以使用Image庫中的filter方法顯現出來,語法是img = Image.open("C:\\Users\\yangp\\Desktop\\612474963277897033.jpg");img.filter(ImageFilter.FIND_EDGES);img.show();
