第一步,安装OPENCV 见最新openCV-Python安装教程(opencv-python版本4.4.0, Python版本: 3.9)_python安装opencv_这个人不是画家的博客-CSDN博客
第二步,下面是修正过后的Python 将文件夹下面所有的图片转换成灰色小图像,用于存正片用的。
import os
from skimage.color import rgb2gray
import numpy as np
import skimage.io as io
import matplotlib.pyplot as plt
import cv2def convert_gray(f, **args): # 图片处理与格式化的函数rgb = io.imread(f) # 读取图片gray = rgb2gray(rgb) # 将彩色图片转换为灰度图片Image = cv2.resize(gray, (50, 50)) # 调整大小,图像分辨率为40*40# cv2.imshow("img-org", Image) # 显示该图像return Imageif __name__ == '__main__':'''批量转灰度图'''datapath = r'D:\WORK\QT\OPENCV3.41\opencv_bin\samples\Tube' # 图片所在的路径str = datapath +'\pos\\'+ '/*.jpg' # 识别.jpg的图像coll = io.ImageCollection(str, load_func=convert_gray) # 批处理print("===>",coll[0].shape)# img_data = np.random.random((1000, 1000))# plt.imshow(img_data)# plt.show()# plt.imsave('D:\WORK\QT\OPENCV3.41\opencv_bin\samples\Tube\pos-1\\'+np.str_(5)+'-runoob-test.png', img_data)length = len(coll)print("===>",length)for i in range(length):img_float = coll[i].astype(np.float32) * 255.0#cv2.imshow("img-org", img_float) #io.show()io.imsave(datapath+'\pos-1\\' + np.str_(i+1) + '.jpg', img_float.astype(np.uint8)) # 保存图片 coll[i]#cv2.imwrite(datapath+'\pos-1\\' + np.str_(i+1) + '.jpg',img_float)
第三步 生成文件信息
import os
def create_pos_n_neg():for file_type in ['pos-1']: #此处修改neg或pos即可for img in os.listdir(file_type):if (file_type == 'neg-1'):line = file_type + '/' + img + '\n'with open('bg.txt', 'a') as f:f.write(line)elif (file_type == 'pos-1'):line = file_type + '/' + img + ' 1 0 0 50 50\n'with open('info.txt', 'a') as f:f.write(line)if __name__ == '__main__':create_pos_n_neg()print('描述文件已生成!')