图像边缘算法

算法描述:将当前像素与邻接的下边和右边像素进行比较,如果相似设置为白色,否则设置为黑色。

欧氏距离算法,如果两个像素的欧氏距离小于某个常数的阀值则认定为相似。

两个n维向量a(x11, x12, ..., x1n)b(x21, x22, ..., x2n)间的欧氏距离如下公式:

$$d=\sqrt{\sum_{k=1}^n(x_{1k}-x_{2k})^2}$$

Python代码实现

1
2
3
4
5
6
7
8
9
10
11
12

def get_euclidean_distance(x, y):
"""
计算欧氏距离
:param x:
:param y:
:return:
"""
myx = np.array(x)
myy = np.array(y)
return np.sqrt(np.sum((myx - myy) * (myx - myy)))

阀值设置为16

原始图片
原始图片

描边图片
描边图片

完整代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#! /usr/bin/python
# -*- coding:utf-8 -*-
"""
@author: abc
@file: euclidean_distance.py
@date: 2016-12-09
@desc: 欧氏距离
"""
__author__ = "abc"

import cv2
import numpy as np


def get_euclidean_distance(x, y):
"""
计算欧氏距离
:param x:
:param y:
:return:
"""
myx = np.array(x)
myy = np.array(y)
return np.sqrt(np.sum((myx - myy) * (myx - myy)))


def handle_img(imgpath):
"""
handle_img
:param imgpath:
:return:
"""
myimg1 = cv2.imread(imgpath)

cv2.namedWindow('img1')
cv2.imshow('img1', myimg1)
cv2.waitKey()
cv2.destroyAllWindows()

w = myimg1.shape[1]
h = myimg1.shape[0]

sz1 = w
sz0 = h

flag = 16

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 xrange(sz0 - 1):
for x in xrange(sz1 - 1):
myhere = myimg1[y, x, :]
mydown = myimg1[y + 1, x, :]
myright = myimg1[y, x + 1, :]

lmyhere = myhere
lmyright = myright
lmydown = mydown

if get_euclidean_distance(lmyhere, lmydown) > flag and get_euclidean_distance(lmyhere, lmyright) > flag:
myimg2[y, x, :] = black
elif get_euclidean_distance(lmyhere, lmydown) <= flag and get_euclidean_distance(lmyhere, lmyright) <= flag:
myimg2[y, x, :] = white
else:
myimg2[y, x, :] = centercolor

cv2.namedWindow('img2')
cv2.imshow('img2', myimg2)
cv2.waitKey()
cv2.destroyAllWindows()


if __name__ == "__main__":
imgpath = "/home/abc/Projects/machine_learning/img/test4.png"
handle_img(imgpath)

http://blog.sina.com.cn/s/blog_52510b1d01015nrg.html