# 初识图像处理：从入门到改行

import cv2

import numpy as np

# 定义绘图函数

def imshow(name, img):

cv2.imshow(name, img)

cv2.waitKey(0)

cv2.destroyAllWindows()

1

2

3

4

5

6

7

8

cv2.imshow(）画个图还要一套组合拳，接化发，咱年轻人顶不住，先给个函数打包定义一下。

# ref = cv2.cvtColor(img_num, cv2.COLOR_BGR2GRAY)转换成灰度图

imshow('img_num',img_num)

1

2

3

4

5

# cv2.threshold返回两个值 第二个值是我需要的处理后的图像

img_num_bin = cv2.threshold(img_num,10,255,cv2.THRESH_BINARY_INV)[1]

imshow('img_num_bin',img_num_bin)

1

2

3

4

# 返回的list中每个元素都是图像中的一个轮廓

num_cntslist, =cv2.findContours(img_num_bin.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(img_num_bin, num_cnts_list, -1, (0,0,255), 3)

imshow('draw_img_num',img_num_bin)

1

2

3

4

5

num_rect_list = num_cnts_sort(num_cnts_list)

1

num_cnts_sort是我自定义的函数，用来给轮廓排序，并且按一定的顺序返回

def num_cnts_sort(list,right=1,up=0):

# up=1表示从上往下，right=1表示从左往右，-1表示反过来

``````reverse = False
if up==-1 or right== -1:
reverse = True

if up == 0:
# 左右方向排序 权重选x
i = 0

if right == 0:
i = 1

# 找到的轮廓用外接矩形框起来 cv2.boundingRect(c)返回x,y,w,h
boundingBoxs = [cv2.boundingRect(c) for c in list] #生成器
# sorted(输入序列，排序规则，reverse=True 由小到大否则由大到小）
# lambda 匿名函数 输入序列的每个元素 输出b[i]
boxs = sorted(boundingBoxs,key= lambda b: b[i],reverse=reverse )

return boxs``````

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

for num_rect in num_rect_list:

(x,y,w,h)=num_rect

num_rect_img = cv2.rectangle(img_num_bin.copy(),(x,y),(x+w,y+h),(255,0,0),2)

imshow('num_rect_img',num_rect_img)

1

2

3

4

5

# 把图片和数字对应

num_rect_dic = {}

for (i,num_rect) in enumerate(num_rect_list):

(x, y, w, h) = num_rect

``````num_rect_item = img_num_bin[y:y+h,x:x+w]
num_rect_item = num_resize(num_rect_item,h_size=88)
# 把数字和截下来的图像对应
num_rect_dic[i]=num_rect_item
imshow('num_rect_item', num_rect_item)``````

1

2

3

4

5

6

7

8

9

10

num_resize为自定义函数，输入高或宽自动计算缩放

def num_resize(img,w_size=0,h_size=0):

(w,h)=img.shape # size返回总元素个数 和matlab不一样

if w_size == 0:

r = h_size/float(h)

w_size = int(rh)

if h_size == 0:

r = w_size/float(w)

h_size = int(wh)

resized = cv2.resize(img,(w_size,h_size))

return resized

1

2

3

4

5

6

7

8

9

10

11

# 读取图像

bank_img_gray = cv2.cvtColor(bank_img,cv2.COLOR_BGR2GRAY)

imshow('bank_img',bank_img)

imshow('bank_img_gray',bank_img_gray)

# 定义卷积核

rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3)) # 矩形卷积核

sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))

# 顶帽操作 突出明亮的部分

bank_img_tophat = cv2.morphologyEx(bank_img_gray,cv2.MORPH_TOPHAT, rectKernel)

imshow('bank_img_tophat',bank_img_tophat)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

# 二值化 cv2.THRESH_OTSU会选择合适的阈值进行二值化 cv2.threshold返回的是两个元素 第二个是处理后的图像

bank_img_bin = cv2.threshold(bank_img_grad_abs, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

imshow('s',bank_img_bin)