图像边缘检测-sobel算子
from PIL import Image, ImageFont
import numpy as np
import matplotlib.pyplot as pyplot
import pylab
im =Image.open(‘Bikesgray.jpg’)#记得要用灰度图,如果是彩色图需要转换成灰度图
im=im.convert(‘L’)
pyplot.imshow(im, cmap=pyplot.cm.gray)#输出图片可能颜色有问题,用cmap=pyplot.cm.gray进行改颜色还有方向问题,也可以通过调整
pylab.show()
w,h = im.size
res = np.zeros((w, h))
sobel_x =[[-1, 0, 1],[-2, 0, 2],[-1, 0, 1]]
sobel_y =[[-1, -2, 1],[0, 0, 0],[1, 2, -1]]
for x in range(1, (w-1)):
for y in range(1, (h-1)):
sub =[[im.getpixel((x-1, y-1)), im.getpixel((x-1, y)), im.getpixel((x-1, y+1))],
[im.getpixel((x, y-1)), im.getpixel((x, y)), im.getpixel((x, y+1))],
[im.getpixel((x+1, y-1)), im.getpixel((x+1, y)), im.getpixel((x+1, y+1))]]
sub = np.array(sub)
roberts_x = np.array(sobel_x)
roberts_y = np.array(sobel_y)
var_x =sum(sum(sub * sobel_x))
var_y = sum(sum(sub * sobel_y))
var = abs(var_x) + abs(var_y)
res[x][y] = var
pyplot.imshow(res, cmap=pyplot.cm.gray)
pylab.show()