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();