Last active
September 4, 2020 15:58
-
-
Save HarshitRuwali/31e7dd91a2839b30e8aad5f8a2d3e115 to your computer and use it in GitHub Desktop.
Extract the Images from the CSV file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import cv2 | |
import mxnet as mx | |
import pandas as pd | |
import random | |
import os | |
curdir = os.path.abspath(os.path.dirname(__file__)) | |
def gen_record(csvfile,channel): | |
data = pd.read_csv(csvfile,delimiter=',',dtype='a') | |
labels = np.array(data['emotion'],np.float) #change according to your csv file | |
# print(labels,'\n',data['emotion']) | |
imagebuffer = np.array(data['pixels']) | |
images = np.array([np.fromstring(image,np.uint8,sep=' ') for image in imagebuffer]) | |
del imagebuffer | |
num_shape = int(np.sqrt(images.shape[-1])) | |
images.shape = (images.shape[0],num_shape,num_shape) | |
# img=images[0];cv2.imshow('test',img);cv2.waitKey(0);cv2.destroyAllWindow();exit() | |
dirs = set(data['Usage']) | |
subdirs = set(labels) | |
class_dir = {} | |
for dr in dirs: | |
dest = os.path.join(curdir,dr) | |
class_dir[dr] = dest | |
if not os.path.exists(dest): | |
os.mkdir(dest) | |
data = zip(labels,images,data['Usage']) | |
for d in data: | |
destdir = os.path.join(class_dir[d[-1]],str(int(d[0]))) | |
if not os.path.exists(destdir): | |
os.mkdir(destdir) | |
img = d[1] | |
filepath = unique_name(destdir,d[-1]) | |
print('[^_^] Write image to %s' % filepath) | |
if not filepath: | |
continue | |
sig = cv2.imwrite(filepath,img) | |
if not sig: | |
print('Error') | |
exit(-1) | |
def unique_name(pardir,prefix,suffix='jpg'): | |
filename = '{0}_{1}.{2}'.format(prefix,random.randint(1,10**8),suffix) | |
filepath = os.path.join(pardir,filename) | |
if not os.path.exists(filepath): | |
return filepath | |
unique_name(pardir,prefix,suffix) | |
if __name__ == '__main__': | |
filename = '*.csv' #change to the csv file name | |
filename = os.path.join(curdir,filename) | |
gen_record(filename,1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment