python批量预处理图片

来源:互联网 发布:安全风险评估矩阵 编辑:程序博客网 时间:2024/06/13 04:18

1.create_negative.py


  1. #功能描述:在每个负样本图片中,选择若干个小块,并存入相应的文件夹中。  
  2. # -*- coding: UTF-8 -*-  
  3. import numpy as np   #numpy:提供矩阵运算功能的库  
  4. import cv2     #cv2:opencv库  
  5. import os      #os:操作系统相关的信息模块  
  6.   
  7. data_base_dir = "/home/xiao/code/CNN_face_detection/face_pictures/image-noface"   #存放原始图片地址  
  8. start_neg_dir = 1  
  9. end_neg_dir = 50  
  10. file_list = []      #建立新列表,用于存放图片名  
  11. for file in os.listdir(data_base_dir):   #指定目录:data_base_dir中内容  
  12.     if file.endswith(".jpg"):      #文件以‘.jpg',结尾  
  13.         file_list.append(file)     #将jpg图片文件全部全部存入file_list列表中  
  14.  
  15. number_of_pictures = len(file_list)     #len(a):列表a长度  
  16. print "number_of_pictures:", number_of_pictures   #输出图片个数  
  17. # ============== create directories ==================================  
  18. directory = '/home/xiao/code/CNN_face_detection/face_pictures/negatives/negative_'  #开始路径  
  19. for cur_file in range(150):   #range(150)表示cur_file从1循环取到49  
  20.     path = directory + str(cur_file).zfill(2)  #str,zfill(2),字符串宽度为2  
  21.     if not os.path.exists(path):    #如果路径path不存在  
  22.         os.makedirs(path)           #创建path路径  
  23. # ============== create negatives =====================================  
  24. for current_neg_dir in range(start_neg_dir, end_neg_dir + 1): #current_neg_dir从1循环取到50  
  25.     save_image_number = 0  
  26.     #存储图片地址,相对文件名从negative_1 ~~ negative_50  
  27.     save_dir_neg = "/home/xiao/code/CNN_face_detection/face_pictures/negatives/negative_" + str(current_neg_dir).zfill(2)  
  28.     #取300个图片,(0,300),(300,600),(600,900).....  
  29.     for current_image in range((current_neg_dir - 1)*300, (current_neg_dir - 1)*300 + 300):   
  30.         if current_image % 10 == 0:      #每处理100张,显示1次  
  31.             print "Processing image number " + str(current_image)  
  32.         read_img_name = data_base_dir + '/' + file_list[current_image].strip() #strip():移除字符串开头和结尾处空格  
  33.         img = cv2.imread(read_img_name)      #读取图片  
  34.         height, width, channels = img.shape  #取长宽,通道数  
  35.   
  36.         crop_size = min(height, width) / 2  #从短边中间开始  
  37.   
  38.         while crop_size >= 12:  
  39.             for start_height in range(0, height, 100):   #从0开始到'height-1'结束,步长100  
  40.                 for start_width in range(0, width, 100):  
  41.                     if (start_width + crop_size) > width:  
  42.                         break  
  43.                     cropped_img = img[start_height : start_height + crop_size, start_width : start_width + crop_size]  
  44.                     file_name = save_dir_neg + "/neg" + str(current_neg_dir).zfill(2) + "_" + str(save_image_number).zfill(6) + ".jpg"  
  45.                     cv2.imwrite(file_name, cropped_img)  
  46.                     save_image_number += 1  
  47.             crop_size *= 0.5  
  48.   
  49.         if current_image == (number_of_pictures - 1):  
  50.             break    #跳出本层循环体,从而提前结束本层循环  


2.create_positive.py view plai copy

  1. #功能描述:在每个正样本图片中,选择指定区域,并存入相应的文件夹中。  
  2. # -*- coding: UTF-8 -*-    
  3. import numpy as np   #numpy:提供矩阵运算功能的库  
  4. import cv2       #cv2:opencv库  
  5. import os        #os:操作系统相关的信息模块  
  6. #/home/xiao...:绝对地址,/home/xiao...:相对地址;  
  7. data_base_dir = "/home/xiao/code/CNN_face_detection/face_pictures"     #存放原始图片地址  
  8. save_dir = "/home/xiao/code/CNN_face_detection/face_pictures/positives"  #保存生成图片地址  
  9. #存放图片名及人脸区域(x,y,w,h)的txt文件地址  
  10. read_file_name_rect = "/home/xiao/code/CNN_face_detection/face_pictures/pos.txt"    
  11.   
  12. # =========== read rect file ===============  
  13. with open(read_file_name_rect, "r") as ins:#以只读方式打开文件read_file_name_rect,并将其赋值给ins  
  14.     array_rect = []    #定义一个空列表,读文件中每行,作为其一个元素  
  15.     for line in ins:   #依次读ins中每个元素  
  16.         array_rect.append(line)      #将line元素,添加到列表array_rect最后  
  17. array_rect = array_rect[1:]   # 切片,舍弃第0个,从第1个取到最后一个  
  18. number_of_lines = len(array_rect)  #取列表长度,即列表中有多少个元素。  
  19. print "number_of_lines:", number_of_lines  #输出列表元素个数  
  20.   
  21. # =========== Start processing ===============  
  22. save_file_number = 0    #定义变量,表示保存图片的个数  
  23.   
  24. for current_rect in range(0, number_of_lines): #current_rect依次取值0,1,2.....number_of_lines-1  
  25.     if current_rect % 10 == 0:       #每10次输出一次  
  26.         print "Processing rect number " + str(current_rect)  
  27.     current_info = array_rect[current_rect].split()#在列表中,以空格为界,对字符串进行切片处理  
  28.     current_image_name = current_info[0]      #图片名  
  29.     #(x,y)表示图片左上角坐标,w表示宽,h表示高  
  30.     x = max(0int(current_info[1]))  
  31.     y = max(0int(current_info[2]))  
  32.     w = int(current_info[3])  
  33.     h = int(current_info[4])  
  34.   
  35.     if current_image_name is None:   #检查图片名是否存在  
  36.         continue          #continue:结束本次循环,break:结束当前整个循环  
  37.     read_img_name = data_base_dir + '/' + current_image_name   #右边进行拼接,得到左边文件名  
  38.     if not os.path.exists(read_img_name):     #检查文件是否存在  
  39.         continue  
  40.     img = cv2.imread(read_img_name)     #调用opencv读取图片  
  41.     cropped_img = img[y : y + h, x : x + w] #取原图片(y:y+h,x:x+w)区域,作为裁剪新图片  
  42.     #将新图片文件名和地址写入file_name中,zfill(width),width:最后的字符串宽度  
  43.     file_name = save_dir + "/pos_" + str(save_file_number).zfill(6) + ".jpg"  
  44.     save_file_number += 1  
  45.     cv2.imwrite(file_name, cropped_img)  #保存图片(cropped_img)到指定位置(file_name)   


3.shuffle_write_negatives.py
 view plain copy

  1. #功能描述:给定存放负样本图片的文件夹地址,将其图片路径、图片名和标签写入txt文件中。  
  2. # -*- coding: UTF-8 -*-    
  3. import os          #os:操作系统相关的信息模块  
  4. import random      #导入随机函数  
  5.   
  6. trainingNet = 48   #选择网络模型型号  
  7. #存放原始图片地址  
  8. data_base_dir = "/home/xiao/code/CNN_face_detection/face_pictures/negatives"   
  9.   
  10. if trainingNet == 12:  
  11.     start_neg_dir = 1   #用于选择相对文件夹  
  12.     end_neg_dir = 6  
  13.     # 读取图片文件,并将图片地址、图片名和标签写到txt文件中  
  14.     write_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/all_negatives.txt'  
  15. elif trainingNet == 24:  
  16.     start_neg_dir = 4  
  17.     end_neg_dir = 9  
  18.     # load and open files to read and write  
  19.     write_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/all_negatives_24c.txt'  
  20. elif trainingNet == 48:  
  21.     start_neg_dir = 7  
  22.     end_neg_dir = 13  
  23.     # load and open files to read and write  
  24.     write_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/all_negatives_48c.txt'  
  25.   
  26. write_file = open(write_file_name, "w")   #以只写方式打开write_file_name文件  
  27. file_list = []      #建立列表,用于保存图片信息  
  28.   
  29. for current_neg_dir in range(start_neg_dir, end_neg_dir + 1):  
  30.     current_dir = data_base_dir + '/negative_' + str(current_neg_dir).zfill(2)  
  31.   
  32.     for file in os.listdir(current_dir):   #file为current_dir当前目录下图片名  
  33.         if file.endswith(".jpg"):          #如果file以jpg结尾  
  34.             write_name = current_dir + '/' + file + ' ' + str(0) #图片路径 + 图片名 + 标签  
  35.             file_list.append(write_name)   #将write_name添加到file_list列表最后  
  36.   
  37. random.shuffle(file_list)   #将列表中所有元素随机排列  
  38. number_of_lines = len(file_list)  #列表中元素个数  
  39. print number_of_lines  
  40.   
  41. #将图片信息写入txt文件中,逐行写入  
  42. for current_line in range(number_of_lines):  
  43.     write_file.write(file_list[current_line] + '\n')  
  44.   
  45. write_file.close()   #关闭文件  


4.shuffle_write_positives.py
 view plain copy

  1. #功能描述:给定存放正样本图片的文件夹地址,将其图片路径、图片名和标签写入txt文件中。  
  2. # -*- coding: UTF-8 -*-  
  3. import os          #os:操作系统相关的信息模块  
  4. import random      #导入随机函数  
  5. #存放原始图片地址  
  6. data_base_dir = "/home/xiao/code/CNN_face_detection/face_pictures/positives"     
  7. file_list = []      #建立列表,用于保存图片信息  
  8. #读取图片文件,并将图片地址、图片名和标签写到txt文件中  
  9. write_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/all_positives.txt'  
  10. write_file = open(write_file_name, "w")   #以只写方式打开write_file_name文件  
  11.   
  12. for file in os.listdir(data_base_dir):  #file为current_dir当前目录下图片名  
  13.     if file.endswith(".jpg"):      #如果file以jpg结尾  
  14.         write_name = data_base_dir + '/' + file + ' ' + str(1)  #图片路径 + 图片名 + 标签  
  15.         file_list.append(write_name)    #将write_name添加到file_list列表最后  
  16.   
  17. random.shuffle(file_list)   #将列表中所有元素随机排列  
  18. number_of_lines = len(file_list)  #列表中元素个数  
  19. #将图片信息写入txt文件中,逐行写入  
  20. for current_line in range(number_of_lines):  
  21.     write_file.write(file_list[current_line] + '\n')  
  22. #关闭文件  
  23. write_file.close()     

5.write_train_val.py view plain copy

  1. #功能描述:读取正样本和负样本图片,分别取其一部分作为验证集,剩余部分作为训练集。  
  2. #将用于验证的图片拷贝到val文件夹下,其图片名和标签写入val.txt文件中,训练集同上。  
  3. # -*- coding: UTF-8 -*- 
  4. import os       #os:操作系统相关的信息模块  
  5. import cv2      #cv2:opencv库  
  6. import shutil   #shutil:一种高层次的文件操作工具,有较强文件复制和删除功能  
  7. import random   #导入随机函数  
  8.   
  9. trainingNet = 48   #选择网络模型型号  
  10. # 打开文件进行读写  
  11. # =================== face_12c =================================  
  12. if trainingNet == 12:  
  13.     pos_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/all_positives.txt' #读取正样本路径  
  14.     neg_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/all_negatives.txt' #读取负样本路径  
  15.     train_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/train_12c' #训练图片存放地址  
  16.     val_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/val'    #验证图片存放地址  
  17.     write_train_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/train_12c.txt' #写入训练样本路径  
  18.     write_train = open(write_train_name, "w")   #以只写方式打开txt文件,写入训练样本相关信息  
  19.     write_val_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/val.txt'  
  20.     write_val = open(write_val_name, "w")  
  21.   
  22. # =================== face_24c =================================  
  23. elif trainingNet == 24:  
  24.     pos_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/all_positives.txt'  
  25.     neg_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/all_negatives_24c.txt'  
  26.     train_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/train_val/train_24c'  
  27.     val_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/train_val/val_24c'  
  28.     write_train_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/train_24c.txt'  
  29.     write_train = open(write_train_name, "w")  
  30.     write_val_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/val_24c.txt'  
  31.     write_val = open(write_val_name, "w")  
  32.   
  33. # =================== face_48c =================================  
  34. elif trainingNet == 48:  
  35.     pos_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/all_positives.txt'  
  36.     neg_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/all_negatives_48c.txt'  
  37.     train_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/train_val/train_48c'  
  38.     val_file_name = '/home/xiao/code/CNN_face_detection/face_pictures/train_val/val_48c'  
  39.     write_train_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/train_48c.txt'  
  40.     write_train = open(write_train_name, "w")  
  41.     write_val_name = '/home/xiao/code/CNN_face_detection/face_pictures/data/val_48c.txt'  
  42.     write_val = open(write_val_name, "w")  
  43.   
  44. pos = []  
  45. with open(pos_file_name, "r") as ins:   #以只读方式打开文件pos_file_name,并将其赋值给ins  
  46.     for line in ins:          #依次读ins中每个元素  
  47.         pos.append(line)      #将line元素,添加到列表pos最后  
  48.   
  49. neg = []  
  50. with open(neg_file_name, "r") as ins:  
  51.     for line in ins:  
  52.         neg.append(line)   
  53.   
  54. number_of_pos = len(pos)  
  55. number_of_neg = len(neg)  
  56.   
  57. #分别取正负样本前500个图片,作为验证集  
  58. val = []  
  59. val[0:500] = pos[0:500] #切片,取正样本前500个图片,作为验证集前500个  
  60. val[500:1000] = neg[0:500] #取负样本前500个图片,作为验证集后500个  
  61. random.shuffle(val)    #将列表中所有元素随机排列  
  62. for current_image in range(1000):  
  63.     source = val[current_image][0:-3]   #从val中取图片文件名  
  64.     image_file_name = val[current_image][48:-3]     #取图片文件名  
  65.     label = int(val[current_image][-2:-1])   #取图片标签  
  66.     destination = val_file_name     #目标地址  
  67.     shutil.copy(source, destination)    #将图片拷贝到val文件夹中  
  68.     image_file_complete = destination + '/' + image_file_name  
  69.     #将图片信息写入txt文件中,逐行写入  
  70.     write_val.write(image_file_name + ' ' + str(label) + '\n')     
  71. write_val.close()  
  72.   
  73. #训练数据  
  74. train = []  
  75. train[0:number_of_pos - 500] = pos[500:]  #将剩余正样本作为训练集  
  76. train[number_of_pos - 500:] = neg[500:]   #将剩余负样本作为训练集  
  77. random.shuffle(train)  
  78. number_of_train_data = len(train)  
  79.   
  80. #将训练图片信息写入train.txt  
  81. for current_image in range(number_of_train_data):  
  82.     if current_image % 1000 == 0:  #每处理1000张,显示1次  
  83.         print 'Processing training data : ' + str(current_image)  
  84.     source = train[current_image][0:-3]     
  85.     image_file_name = train[current_image][48:-3]      
  86.     label = train[current_image].strip()[-1:]    
  87.     destination = train_file_name  
  88.     shutil.copy2(source, destination)    #将图片拷贝到train文件夹中  
  89.     write_content = image_file_name + ' ' + label + '\n'  
  90.     write_train.write(write_content)      #写入训练图片信息到txt  
  91. write_train.close()     

6.face-lmdb.sh

  1. # -*- coding: UTF-8 -*-
  2. #!/usr/bin/env sh
  3. # Create the face_48 lmdb inputs
  4. # N.B. set the path to the face_48 train + val data dirs

  5. EXAMPLE=/home/ubuntu/Downloads/CNN
  6. DATA=/home/ubuntu/Downloads/CNN  #数据所在目录
  7. TOOLS=/home/ubuntu/caffe/build/tools #caffe安装路径

  8. TRAIN_DATA_ROOT=/home/ubuntu/Downloads/CNN/train/
  9. VAL_DATA_ROOT=/home/ubuntu/Downloads/CNN/val/

  10. RESIZE=true
  11. if $RESIZE; then
  12.     RESIZE_HEIGHT=227 #裁剪图片尺寸
        RESIZE_WIDTH=227
    else
        RESIZE_HEIGHT=0
        RESIZE_WIDTH=0
    fi

    if [ ! -d "$TRAIN_DATA_ROOT" ]; then
      echo "Error: TRAIN_DATA_ROOT is not a path to a directory: $TRAIN_DATA_ROOT"
      echo "Set the TRAIN_DATA_ROOT variable in create_face_48.sh to the path" \
           "where the face_48 training data is stored."
      exit 1
    fi

    if [ ! -d "$VAL_DATA_ROOT" ]; then
      echo "Error: VAL_DATA_ROOT is not a path to a directory: $VAL_DATA_ROOT"
      echo "Set the VAL_DATA_ROOT variable in create_face_48.sh to the path" \
           "where the face_48 validation data is stored."
      exit 1
    fi

    echo "Creating train lmdb..."
    GLOG_logtostderr=1 $TOOLS/convert_imageset \
        --resize_height=$RESIZE_HEIGHT \
        --resize_width=$RESIZE_WIDTH \
        --shuffle \
        $TRAIN_DATA_ROOT \
        $DATA/t_train.txt \
        $EXAMPLE/face_train_lmdb

    echo "Creating val lmdb..."
    GLOG_logtostderr=1 $TOOLS/convert_imageset \
        --resize_height=$RESIZE_HEIGHT \
        --resize_width=$RESIZE_WIDTH \
        --shuffle \
        $VAL_DATA_ROOT \
        $DATA/t_val.txt \
        $EXAMPLE/face_val_lmdb

    echo "Done."
    Status API Training Shop Blog About    

原创粉丝点击