def pre_img(image): myimage = image.convert('L') # 转换成灰度图 myimage = np.array(myimage) # print(myimage.shape) ret, img1 = cv.threshold(myimage, 100, 255, cv.THRESH_BINARY_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-08 07:06:00 浏览: 66
MyImage_Sliding.zip
这段代码的作用是对输入的图像进行预处理,包括转换成灰度图、二值化、膨胀、剔除小连通域、调整大小等。下面是改写后的单个代码,并附加了每一步处理图片的输出:
```python
import cv2 as cv
import numpy as np
def pre_img(image):
# 转换成灰度图
myimage = image.convert('L')
myimage = np.array(myimage)
# 二值化
ret, img1 = cv.threshold(myimage, 100, 255, cv.THRESH_BINARY_INV)
# 膨胀
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)
# 调整大小
img5 = cv.resize(img2, (28, 28))
# 输出每一步处理后的图片
cv.imshow('myimage', myimage)
cv.imshow('img1', img1)
cv.imshow('img2', img2)
cv.imshow('img5', img5)
cv.waitKey(0)
cv.destroyAllWindows()
# 返回预处理后的图像
return img5
# 加载图片
img = cv.imread('test.png')
# 预处理图片
img_pre = pre_img(img)
# 将数据类型由uint8转为float32
img = img_pre.astype(np.float32)
# 图片数据归一化
img = img / 255
```
阅读全文