下载
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)