python多进程读图提取特征存npy


Posted in Python onMay 21, 2019

本文实例为大家分享了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 tf
 
image_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'):
     continue
    image = 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_n
 features = [] #存放提取到的特征
 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 #下标计数加1
   str_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)/3600
 print('用时:%.6f 小时'% time_h)
 print ("读图提取特征存npy,运行结束!")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
简单介绍Python中用于求最小值的min()方法
May 15 Python
深入解析Python中的上下文管理器
Jun 28 Python
Python三种遍历文件目录的方法实例代码
Jan 19 Python
python如何压缩新文件到已有ZIP文件
Mar 14 Python
Python Gitlab Api 使用方法
Aug 28 Python
Spring实战之使用util:命名空间简化配置操作示例
Dec 09 Python
Python + Requests + Unittest接口自动化测试实例分析
Dec 12 Python
对tensorflow中的strides参数使用详解
Jan 04 Python
keras实现调用自己训练的模型,并去掉全连接层
Jun 09 Python
python 贪心算法的实现
Sep 18 Python
关于Python中*args和**kwargs的深入理解
Aug 07 Python
Python可视化神器pyecharts绘制水球图
Jul 07 Python
Python中使用pypdf2合并、分割、加密pdf文件的代码详解
May 21 #Python
python+selenium实现简历自动刷新的示例代码
May 20 #Python
图文详解python安装Scrapy框架步骤
May 20 #Python
Python配置虚拟环境图文步骤
May 20 #Python
Python检测数据类型的方法总结
May 20 #Python
Python中的引用知识点总结
May 20 #Python
Python函数和模块的使用总结
May 20 #Python
You might like
PHP APC的安装与使用详解
2013/06/13 PHP
浅析php变量修饰符static的使用
2013/06/28 PHP
php获取指定(访客)IP所有信息(地址、邮政编码、国家、经纬度等)的方法
2015/07/06 PHP
php版阿里大于(阿里大鱼)短信发送实例详解
2016/11/30 PHP
基于Laravel5.4实现多字段登录功能方法示例
2017/08/11 PHP
PHP读取、解析eml文件及生成网页的方法示例
2017/09/04 PHP
PHP依赖注入原理与用法分析
2018/08/21 PHP
关于Laravel参数验证的一些疑与惑
2019/11/19 PHP
PHP dirname功能及原理实例解析
2020/10/28 PHP
javascript 图片上一张下一张链接效果代码
2010/03/12 Javascript
ASP 过滤数组重复数据函数(加强版)
2010/05/31 Javascript
JQuery入门—编写一个简单的JQuery应用案例
2013/01/03 Javascript
js动态添加onclick事件可传参数与不传参数
2014/07/29 Javascript
详解js中构造流程图的核心技术JsPlumb
2015/12/08 Javascript
jQuery Validate表单验证入门学习
2015/12/18 Javascript
浅谈Sticky组件的改进实现
2016/03/22 Javascript
JavaScript基础之AJAX简单的小demo
2017/01/29 Javascript
JavaScript实现重力下落与弹性效果的方法分析
2017/12/20 Javascript
JQuery扩展对象方法操作示例
2018/08/21 jQuery
ES6的异步操作之promise用法和async函数的具体使用
2019/12/06 Javascript
vue项目中在可编辑div光标位置插入内容的实现代码
2020/01/07 Javascript
[02:08]2018年度CS GO枪械皮肤设计大赛优秀作者-完美盛典
2018/12/16 DOTA
Linux系统上Nginx+Python的web.py与Django框架环境
2015/12/25 Python
Python 编码处理-str与Unicode的区别
2016/09/06 Python
Python之日期与时间处理模块(date和datetime)
2017/02/16 Python
Python之读取TXT文件的方法小结
2018/04/27 Python
python3.6利用pyinstall打包py为exe的操作实例
2018/10/31 Python
python SVM 线性分类模型的实现
2019/07/19 Python
python scipy卷积运算的实现方法
2019/09/16 Python
关于pytorch处理类别不平衡的问题
2019/12/31 Python
css3 transform导致子元素固定定位变成绝对定位的方法
2020/03/06 HTML / CSS
英国高级百货公司:Harvey Nichols
2017/01/29 全球购物
巴西图书和电子产品购物网站:Saraiva
2017/06/07 全球购物
任意存:BOXFUL
2018/05/21 全球购物
医药代表个人求职信范本
2013/12/19 职场文书
校园文化艺术节开幕词
2016/03/04 职场文书