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中对象迭代与反迭代的技巧总结
Sep 17 Python
Django中STATIC_ROOT和STATIC_URL及STATICFILES_DIRS浅析
May 08 Python
用xpath获取指定标签下的所有text的实例
Jan 02 Python
WIn10+Anaconda环境下安装PyTorch(避坑指南)
Jan 30 Python
Python redis操作实例分析【连接、管道、发布和订阅等】
May 16 Python
python实现植物大战僵尸游戏实例代码
Jun 10 Python
python ChainMap的使用和说明详解
Jun 11 Python
Python读写文件模式和文件对象方法实例详解
Sep 17 Python
Python的形参和实参使用方式
Dec 24 Python
Python socket聊天脚本代码实例
Jan 02 Python
pytorch 彩色图像转灰度图像实例
Jan 13 Python
Python爬虫制作翻译程序的示例代码
Feb 22 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的FTP学习(三)
2006/10/09 PHP
ThinkPHP使用心得分享-上传类UploadFile的使用
2014/05/15 PHP
PHP通过文件保存和更新信息的方法分析
2019/09/12 PHP
javascript(jquery)利用函数修改全局变量的代码
2009/11/02 Javascript
基于jQuery的仿flash的广告轮播
2010/11/05 Javascript
jQuery1.3.2 升级到jQuery1.4.4需要修改的地方
2011/01/06 Javascript
jQuery find和children方法使用
2011/01/31 Javascript
Visual Studio中js调试的方法图解
2014/06/30 Javascript
jQuery幻灯片特效代码分享--鼠标滑过按钮时切换(2)
2020/11/18 Javascript
JS实现的简易拖放效果示例
2016/12/29 Javascript
Vue.js实现表格动态增加删除的方法(附源码下载)
2017/01/20 Javascript
基于JavaScript实现自定义滚动条
2017/01/25 Javascript
微信小程序 开发之滑块视图容器(swiper)详解及实例代码
2017/02/22 Javascript
angular学习之从零搭建一个angular4.0项目
2017/07/10 Javascript
Vue中如何实现轮播图的示例代码
2017/07/27 Javascript
Angular4学习笔记之准备和环境搭建项目
2017/08/01 Javascript
手把手教你vue-cli单页到多页应用的方法
2018/05/31 Javascript
electron+vue实现div contenteditable截图功能
2020/01/07 Javascript
vue.js+element 默认提示中英文操作
2020/11/11 Javascript
[43:51]2018DOTA2亚洲邀请赛3月30日 小组赛B组 EG VS Secret
2018/03/31 DOTA
给Python的Django框架下搭建的BLOG添加RSS功能的教程
2015/04/08 Python
python中global用法实例分析
2015/04/30 Python
以视频爬取实例讲解Python爬虫神器Beautiful Soup用法
2016/01/20 Python
react+django清除浏览器缓存的几种方法小结
2019/07/17 Python
解决Atom安装Hydrogen无法运行python3的问题
2019/08/28 Python
python实现单链表的方法示例
2019/09/03 Python
Pytorch中的variable, tensor与numpy相互转化的方法
2019/10/10 Python
css3实现二维码扫描特效的示例
2020/10/29 HTML / CSS
在IE6系列等老式浏览器中使用HTML5的新标签实现方案
2012/12/25 HTML / CSS
绿色美容,有机护肤品和化妆品:Safe & Chic
2018/10/29 全球购物
定制别致的瑜伽垫:Sugarmat
2019/06/21 全球购物
小学后勤管理制度
2014/01/14 职场文书
工程质量承诺书范文
2014/03/27 职场文书
代理人委托书
2014/09/16 职场文书
2014年自愿离婚协议书
2014/10/10 职场文书
2016年小学“感恩教师”主题队日活动总结
2016/04/01 职场文书