目录
一、算法描述
算法的基本原理是:将当前像素与邻接的下部和右部进行比较,如果相似,则将当前像素设置为白色,否则设置为黑色。如何判定像素相似呢?应用欧式距离算法,将一个图像的3个色彩分量映射在三维空间中,如果2个像素点的欧氏距离小于某个常数的阈值,就认为它们相似。
二、计算欧氏距离的Python代码
def get_EuclideanDistance(x,y):
myx = np.array(x)
myy = np.array(y)
return np.sqrt(np.sum((myx-myy)*(myx-myy)))
三、完整的代码
import cv2
import numpy as np
fn = r"C:\Users\LIHAO\Pictures\Saved Pictures\bpic26318.jpg"
def get_EuclideanDistance(x,y):
myx = np.array(x)
myy = np.array(y)
return np.sqrt(np.sum((myx-myy)*(myx-myy)))
if __name__ == "__main__":
myimg1 = cv2.imread(fn)
w = myimg1.shape[1]
h = myimg1.shape[0]
sz1 = w
sz0 = h
# 创建空白图像
myimg2 = np.zeros((sz0,sz1,3), np.uint8)
# 对比产生线条
black = np.array([0,0,0])
white = np.array([255,255,255])
centercolor = np.array([125,125,125])
for y in range(sz0-1):
for x in range(sz1-1):
mydown = myimg1[y+1,x,:]
myright = myimg1[y,x+1,:]
myhere = myimg1[y,x,:]
lmyhere = myhere
lmyright = myright
lmydown = mydown
if get_EuclideanDistance(lmyhere,lmydown)>16 and get_EuclideanDistance(lmyhere,lmyright)>16:
myimg2[y,x:] = black
elif get_EuclideanDistance(lmyhere,lmydown)<=16 and get_EuclideanDistance(lmyhere,lmyright)<=16:
myimg2[y,x:] = white
else:
myimg2[y,x:] = centercolor
print(y)
cv2.namedWindow('img2')
cv2.imshow('img2', myimg2)
cv2.waitKey()
cv2.destroyAllWindows()
四、结果
第一张为原图,第二张为计算图像边缘的结果