# -*- coding: utf-8 -*-
"""
Created on Wed Mar 7 11:04:15 2018 @author: markli
"""
import numpy as np;
from PIL import Image;
import matplotlib.pyplot as pyplot;
class ImageFilter:
def __init__(self,filepath):
self.path = filepath; def Filter(self,filtermatrix):
"""步长设定为1"""
img = Image.open(self.path);
#img = img.resize((32,32));
r,g,b = img.split(); #rgb 通道分离
#转为数字矩阵
r_arr = np.array(r);
g_arr = np.array(g);
b_arr = np.array(b); matrix = [r_arr,g_arr,b_arr];
#过滤后的结果矩阵
fm = np.ones((r_arr.shape[0] - filtermatrix.shape[0] + 1,r_arr.shape[1] - filtermatrix.shape[1]+1));
fm_rgb = [];
#卷积运算 实现过滤
for m in matrix:
row = 0;
for i in range(fm.shape[0]):
col = 0;
for j in range(fm.shape[1]):
temp = m[row:row + filtermatrix.shape[0],col:col + filtermatrix.shape[1]];
fm[i][j] = np.sum(np.multiply(temp,filtermatrix));
col = col + 1;
row = row + 1; fm_rgb.append(fm); return fm_rgb;
# #数字矩阵转为RGB通道像素
# r = Image.fromarray(fm_rgb[0]).convert('L');
# g = Image.fromarray(fm_rgb[1]).convert('L');
# b = Image.fromarray(fm_rgb[2]).convert('L');
# image = Image.merge("RGB", (r, g, b));
# #图片显示
# pyplot.imshow(image);
# pyplot.show();
def MergeEdage(self,savepath):
leftmatrix = np.array([[1,0,-1],[1,0,-1],[1,0,-1]]);#左边界
left = self.Filter(leftmatrix);
rightmatrix = np.array([[-1,0,1],[-1,0,1],[-1,0,1]]);#右边界
right = self.Filter(rightmatrix);
w_1,h_1 = left[0].shape; #left 和 right 维数相同,使用哪个都可以
full_edage = [];
for i in range(3):
m = np.hstack((left[i][:,:int(w_1/2)],right[i][:,w_1-int(w_1/2):]));
full_edage.append(m); #数字矩阵转为RGB通道像素
r = Image.fromarray(full_edage[0]).convert('L');
g = Image.fromarray(full_edage[1]).convert('L');
b = Image.fromarray(full_edage[2]).convert('L');
image = Image.merge("RGB", (r, g, b));
#图片显示
pyplot.imshow(image);
pyplot.show();
image.save(savepath); img = ImageFilter("C:\\Users\\yangp\\Desktop\\612474963277897033.jpg");
img.MergeEdage("C:\\Users\\yangp\\Desktop\\fulledage.jpg");
下面给出原图、左边界和右边界识别情况:
最后是将左右边界合并,形成整体:
最后说明一下,其中的过滤矩阵可以扩大,将过滤矩阵值的变化放慢,可以使图像的识别更加细致,在这里本人的电脑配置太低,就不演示了。当然图片的轮廓可以使用Image库中的filter方法显现出来,语法是img = Image.open("C:\\Users\\yangp\\Desktop\\612474963277897033.jpg");img.filter(ImageFilter.FIND_EDGES);img.show();