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函数的参数的默认值所引发的问题的原因
Mar 30 Python
在Python中使用poplib模块收取邮件的教程
Apr 29 Python
Python 爬虫模拟登陆知乎
Sep 23 Python
Pyhton中单行和多行注释的使用方法及规范
Oct 11 Python
python截取两个单词之间的内容方法
Dec 25 Python
Python3 Post登录并且保存cookie登录其他页面的方法
Dec 28 Python
深入了解Python枚举类型的相关知识
Jul 09 Python
解决python中显示图片的plt.imshow plt.show()内存泄漏问题
Apr 24 Python
python可以用哪些数据库
Jun 22 Python
django模型类中,null=True,blank=True用法说明
Jul 09 Python
python 5个实用的技巧
Sep 27 Python
聊聊Python String型列表求最值的问题
Jan 18 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
Protoss兵种介绍
2020/03/14 星际争霸
Thinkphp整合阿里云OSS图片上传实例代码
2019/04/28 PHP
document.onreadystatechange事件的用法分析
2009/10/17 Javascript
EXTJS内使用ACTIVEX控件引起崩溃问题的解决方法
2010/03/31 Javascript
JavaScript下通过的XMLHttpRequest发送请求的代码
2011/06/28 Javascript
jQuery下通过replace字符串替换实现大小图片切换
2012/05/22 Javascript
探讨javascript是不是面向对象的语言
2013/11/21 Javascript
jquery动态添加option示例
2013/12/30 Javascript
jquery mobile动态添加元素之后不能正确渲染解决方法说明
2014/03/05 Javascript
jquery select2的使用心得(推荐)
2016/12/04 Javascript
JS获取当前地理位置的方法
2017/10/25 Javascript
webpack实用小功能介绍
2018/01/02 Javascript
Vue 中axios配置实例详解
2018/07/27 Javascript
Vue 无限滚动加载指令实现方法
2019/05/28 Javascript
jquery.pager.js实现分页效果
2019/07/29 jQuery
为python设置socket代理的方法
2015/01/14 Python
python抓取百度首页的方法
2015/05/19 Python
python3学习笔记之多进程分布式小例子
2018/02/13 Python
Numpy中矩阵matrix读取一列的方法及数组和矩阵的相互转换实例
2018/07/02 Python
Python高级特性——详解多维数组切片(Slice)
2019/11/26 Python
python 负数取模运算实例
2020/06/03 Python
Python钉钉报警及Zabbix集成钉钉报警的示例代码
2020/08/17 Python
CSS3属性 line-clamp控制文本行数的使用
2020/03/19 HTML / CSS
HTML5 实战PHP之Web页面表单设计
2011/10/09 HTML / CSS
Bally巴利中国官网:经典瑞士鞋履、手袋及配饰奢侈品牌
2018/10/09 全球购物
C语言笔试题回忆
2015/04/02 面试题
介绍一下linux文件系统分配策略
2012/11/17 面试题
最新会计专业求职信范文
2014/01/28 职场文书
绿色城市实施方案
2014/03/19 职场文书
霸气队列口号
2014/06/18 职场文书
单位授权委托书范本
2014/09/26 职场文书
考试作弊检讨书1000字(5篇)
2014/10/19 职场文书
群众路线自我剖析范文
2014/11/04 职场文书
《花钟》教学反思
2016/02/17 职场文书
JavaScript流程控制(循环)
2021/12/06 Javascript
从零开始在Centos7上部署SpringBoot项目
2022/04/07 Servers