Python多进程读图提取特征存npy
import multiprocessing
import os, time, random
import numpy as np
import cv2
import os
import sys
from time import ctime
import tensorflow as tfimage_dir = r"D:/sxl/处理图片/汉字分类/train10/" #图像文件夹路径
data_type = 'test'
save_path = r'E:/sxl_Programs/Python/CNN/npy/' #存储路径
data_name = 'Img10' #npy文件名char_set = np.array(os.listdir(image_dir)) #文件夹名称列表
np.save(save_path+'ImgShuZi10.npy',char_set) #文件夹名称列表
char_set_n = len(char_set) #文件夹列表长度read_process_n = 1 #进程数
repate_n = 4 #随机移动次数
data_size = 1000000 #1个npy大小shuffled = True #是否打乱#可以读取带中文路径的图
def cv_imread(file_path,type=0):cv_img=cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1)# print(file_path)# print(cv_img.shape)# print(len(cv_img.shape))if(type==0):if(len(cv_img.shape)==3):cv_img = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)return cv_img#多个数组按同一规则打乱数据
def ShuffledData(features,labels):'''@description:随机打乱数据与标签,但保持数据与标签一一对应'''permutation = np.random.permutation(features.shape[0])shuffled_features = features[permutation,:] #多维shuffled_labels = labels[permutation] #1维return shuffled_features,shuffled_labels#函数功能:简单网格
#函数要求:1.无关图像大小;2.输入图像默认为灰度图;3.参数只有输入图像
#返回数据:1x64*64维特征
def GetFeature(image):#图像大小归一化image = cv2.resize(image,(64,64))img_h = image.shape[0]img_w = image.shape[1]#定义特征向量feature = np.zeros(img_h*img_w,dtype=np.int16)for h in range(img_h):for w in range(img_w):feature[h*img_h+w] = image[h,w]return feature# 写数据进程执行的代码:
def read_image_to_queue(queue):print('Process to write: %s' % os.getpid())for j,dirname in enumerate(char_set): # dirname 是文件夹名称label = np.where(char_set==dirname)[0][0] #文件夹名称对应的下标序号print('序号:'+str(j),'读 '+dirname+' 文件夹...时间:',ctime() )for parent,_,filenames in os.walk(os.path.join(image_dir,dirname)):for filename in filenames:if(filename[-4:]!='.jpg'):continueimage = cv_imread(os.path.join(parent,filename),0)# cv2.imshow(dirname,image)# cv2.waitKey(0)queue.put((image,label))for i in range(read_process_n):queue.put((None,-1))print('读图结束!')return True# 读数据进程执行的代码:
def extract_feature(queue,lock,count):'''@description:从队列中取出图片进行特征提取@queue:先进先出队列lock:锁,在计数时上锁,防止冲突count:计数'''print('Process %s start reading...' % os.getpid())global data_nfeatures = [] #存放提取到的特征labels = [] #存放标签flag = True #标志着进程是否结束while flag:image,label = queue.get() #从队列中获取图像和标签if len(features) >= data_size or label == -1: #特征数组的长度大于指定长度,则开始存储array_features = np.array(features) #转换成数组array_labels = np.array(labels)array_features,array_labels = ShuffledData(array_features,array_labels) #打乱数据lock.acquire() # 锁开始# 拆分数据为训练集,测试集split_x = int(array_features.shape[0] * 0.8)train_data, test_data = np.split(array_features, [split_x], axis=0) # 拆分特征数据集train_labels, test_labels = np.split(array_labels, [split_x], axis=0) # 拆分标签数据集count.value += 1 #下标计数加1str_features_name_train = data_name+'_features_train_'+str(count.value)+'.npy'str_labels_name_train = data_name+'_labels_train_'+str(count.value)+'.npy'str_features_name_test = data_name+'_features_test_'+str(count.value)+'.npy'str_labels_name_test = data_name+'_labels_test_'+str(count.value)+'.npy'lock.release() # 锁释放np.save(save_path+str_features_name_train,train_data)np.save(save_path+str_labels_name_train,train_labels)np.save(save_path+str_features_name_test,test_data)np.save(save_path+str_labels_name_test,test_labels)print(os.getpid(),'save:',str_features_name_train)print(os.getpid(),'save:',str_labels_name_train)print(os.getpid(),'save:',str_features_name_test)print(os.getpid(),'save:',str_labels_name_test)features.clear()labels.clear()if label == -1:break# 获取特征向量,传入灰度图feature = GetFeature(image)features.append(feature)labels.append(label)# # 随机移动4次# for itime in range(repate_n):# rMovedImage = randomMoveImage(image)# feature = SimpleGridFeature(rMovedImage) # 简单网格# features.append(feature)# labels.append(label)print('Process %s is done!' % os.getpid())if __name__=='__main__':time_start = time.time() # 开始计时# 父进程创建Queue,并传给各个子进程:image_queue = multiprocessing.Queue(maxsize=1000) #队列lock = multiprocessing.Lock() #锁count = multiprocessing.Value('i',0) #计数#将图写入队列进程write_sub_process = multiprocessing.Process(target=read_image_to_queue, args=(image_queue,))read_sub_processes = [] #读图子线程for i in range(read_process_n):read_sub_processes.append(multiprocessing.Process(target=extract_feature, args=(image_queue,lock,count)))# 启动子进程pw,写入:write_sub_process.start()# 启动子进程pr,读取:for p in read_sub_processes:p.start()# 等待进程结束:write_sub_process.join()for p in read_sub_processes:p.join()time_end=time.time()time_h=(time_end-time_start)/3600print('用时:%.6f 小时'% time_h)print ("读图提取特征存npy,运行结束!")
Python多进程读图提取特征存npy相关推荐
- python多进程读同一个文件_python 多进程读写文件
import time from multiprocessing import Process, JoinableQueue, cpu_count import csv ####处理一条数据的方法 d ...
- python多进程海量视频提取帧图片
视频提取帧图片 多个视频同时处理 跳帧保存图片 限制进程数防止系统崩溃 一键设置视频目录自动获取全部视频并提取帧图片. CPU打满,系统不卡顿. 源码 #!/usr/bin/env python # ...
- python读图命令与效率汇总
文章目录 python读图命令汇总 各个函数读图效率对比 结果 代码 python读图命令汇总 python可以用来读图的命令有: 库(版本) 函数 opencv-python (4.2.0) cv2 ...
- 使用OpenCV和Python从图像中提取形状
Welcome to the first post in this series of blogs on extracting features from images using OpenCV an ...
- 机器视觉:Caffe Python接口多进程提取特征
想象这样一个场景:服务器上配备了很多GPU显卡,而你又使用的是Caffe,不幸的是,你还选用了Python来写代码,不幸中的不幸是你还要在短时间内处理百万千万规模的图片.那么,问题来了,Caffe本身 ...
- 【读点论文】Image Style Transfer Using Convolutional Neural Networks(将卷积特征图提取语义信息,融合内容和风格的做法)
Image Style Transfer Using Convolutional Neural Networks 以不同风格呈现图像的语义内容是一项困难的图像处理任务.可以说,以前的方法的一个主要限制 ...
- halcon边缘提取颜色相近_初学者福利!三种用Python从图像数据中提取特征的技术...
全文共4073字,预计学习时长8分钟 你之前是否使用过图像数据?也许你想建立自己的物体检测模型,或者仅仅是想统计走进某栋建筑物的人数,使用计算机视觉技术处理图像拥有无穷无尽的可能性. 但数据科学家最近 ...
- 使用DeepWalk从图中提取特征
2019-12-03 15:05:14 目录 数据的图示 不同类型的基于图的特征 节点属性 局部结构特征 节点嵌入 DeepWalk简介 在Python中实施DeepWalk以查找相似的Wikiped ...
- python使用箱图法和业务规则进行异常数据处理并检查预测使用的数据特征是否有字段缺失的情况并补齐
python使用箱图法和业务规则进行异常数据处理并检查预测使用的数据特征是否有字段缺失的情况并补齐 关于预测或者推理的时候特征补齐的情况是这样的: 你在模型训练的时候使用了多少特征,那么在模型预测和推 ...
最新文章
- Qt中关于undefined reference to `vtable for故障总结
- 关于win7禁止标准用户安装软件 AppLocker使用
- Solr建立索引时,过滤HTML标签
- 漫画 | 程序员离职事件始末
- matlab 双音多频 接收端检测到的号码,信号语音论文,关于基于MATLAB的双音多频信号识别相关参考文献资料-免费论文范文...
- apache ignite_Kubernetes集群上的Apache Ignite和Spring第1部分:Spring Boot应用程序
- Delphi XE2 - 点点滴滴设置
- leetcode题解8-盛最多水的容器
- 底部导航栏使用BottomNavigationBar
- 生产环境下戴尔 R820 kvm虚拟化部署二(物理主机系统优化)
- 计算机科学技术专业单片机,计算机科学与技术专业毕业论文---基于单片机的智能浇花系统的设计与实现.docx...
- 电驴显示没有连接服务器,电驴未连接到服务器
- 【实践案例分享】阿里文娱智能营销增益模型 ( Uplift Model ) 技术实践
- CodeForces 1538G : Gift Set 思维 + 二分
- VM虚拟机局域网组网配置
- 有必要升级到php7,升级到 PHP 7.4
- 百度云同同步盘 mac版
- 淡淡de馨香---职业尊严
- Spring学习第4篇:Spring 的依赖注入
- 如何在海量数据中查找最相似的topk样本