Y_INV) # cv.namedWindow('img1',0) # cv.resizeWindow('img1',600,600) # cv.imshow('img1',img1) # print(type(img1)) # print(img1.shape) # print(img1.size) # cv.waitKey(2) kernel1 = np.ones((10, 10), np.uint8) # 做一次膨胀 img2 = cv.dilate(img1, kernel1) # cv.namedWindow('img2', 0) # cv.resizeWindow('img2', 600, 600) # cv.imshow('img2', img2) '剔除小连通域' contours, hierarchy = cv.findContours(img2, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE) # print(len(contours),hierarchy) for i in range(len(contours)): area = cv.contourArea(contours[i]) if area < 150: # '设定连通域最小阈值,小于该值被清理' cv.drawContours(img2, [contours[i]], 0, 0, -1) # cv2.imwrite('img2.jpg', img2) # import pdb;pdb.set_trace() img5 = cv.resize(img2, (28, 28)) # cv.namedWindow('img5', 0) # cv.resizeWindow('img5', 600, 600) # cv.imshow('img5', img5) # cv2.imwrite('img5.jpg', img5) # import pdb;pdb.set_trace() return img5 img_pre = pre_img(img) # # cv.imshow('img_pre', img_pre) # 将数据类型由uint8转为float32 img = img_pre.astype(np.float32) # 图片数据归一化 img = img / 255 改成单个代码,能对原图进行预处理并把每一步处理图片输出
时间: 2023-12-09 16:03:08 浏览: 88
以下是能对原图进行预处理并把每一步处理图片输出的代码:
```python
import cv2 as cv
import numpy as np
def pre_img(img_path):
# 读取原图
img = cv.imread(img_path, cv.IMREAD_GRAYSCALE)
# 图片二值化
_, img1 = cv.threshold(img, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)
# 做一次膨胀
kernel1 = np.ones((10, 10), np.uint8)
img2 = cv.dilate(img1, kernel1)
# 剔除小连通域
contours, hierarchy = cv.findContours(img2, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
for i in range(len(contours)):
area = cv.contourArea(contours[i])
if area < 150:
cv.drawContours(img2, [contours[i]], 0, 0, -1)
# 将图片缩放到28x28
img5 = cv.resize(img2, (28, 28))
# 将数据类型由uint8转为float32
img = img5.astype(np.float32)
# 图片数据归一化
img /= 255
# 输出每一步处理后的图片
cv.imshow('img', img)
cv.imshow('img1', img1)
cv.imshow('img2', img2)
cv.imshow('img5', img5)
cv.waitKey(0)
cv.destroyAllWindows()
return img
# 调用预处理函数
img_path = 'your_image_path'
img_pre = pre_img(img_path)
```
阅读全文