DIP|opencv学习1

下载

pip install opencv-python

pip install numpy

pip install matplotlib

导入模块

import cv2

导入图片

img=cv2.imread("path")

img是numpy中的array

0-255之间:255最亮,0最暗

像素点:[h,w,c]        # BGR 格式

# 灰度处理

gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

cv_show('gray_img', gray_img)

# 均值滤波

blur_img = cv.blur(gray_img, (3, 3))

cv_show('biur_img', blur_img)

# 二值图像

ret, thresh_img = cv.threshold(blur_img, 225, 255, cv.THRESH_BINARY)

cv_show('thresh_img', thresh_img)

# 闭运算

kernel = np.ones((12, 10), np.uint8)

closed_img = cv.morphologyEx(thresh_img, cv.MORPH_CLOSE, kernel)

cv_show('closed_img', closed_img)

# 轮廓检测

contours, hiearchy = cv.findContours(closed_img, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)

contour_img = cv.drawContours(img.copy(), contours, -1, (0, 0, 255), 2)

cv_show('contours_img', contour_img)

# 获取最外层轮廓

out_contours = tuple([contours[i] for i, parent in enumerate(hiearchy[0]) if parent[3] == -1])

out_img = cv.drawContours(img.copy(), out_contours, -1, (0, 0, 255), 2)

cv_show('out_img', out_img)

# 创建画布

canvas = np.zeros((800, 1000, 3), dtype=np.uint8)

# 抠取学号中的字符

for ch in id:

    x, y, width, height = cv.boundingRect(out_contours[letters.index(ch)])

    canvas[char_height:height + char_height, char_width:width + char_width] = img[y:y + height, x:x + width]

    char_width += 70

# 抠取姓名中的字符

char_height += 100

char_width = 20

for ch in name:

    x, y, width, height = cv.boundingRect(out_contours[letters.index(ch.upper())])

    canvas[char_height:height + char_height, char_width:width + char_width] = img[y:y + height, x:x + width]

    char_width += 70

# 显示和保存生成的图片

cv_show('canvas', canvas)

cv.imwrite("student.jpg", canvas)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值