import cv2
import csv
import os
import os.path

def rep_files_init():
	#create a directory to store the RGB datas ouptut
	path_to_script = os.path.dirname(os.path.abspath(__file__))
	if os.path.exists(path_to_script + r"\RGB database") == False:
		os.mkdir(path_to_script + r"\RGB database")
	
	onlyfiles = next(os.walk(path_to_script + r"\frames"))[2] #get the amount of frames previously extracted
	frames_num = len(onlyfiles)-1

	return frames_num


def RGB_dataframe(img, itr):
	face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
	eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

	gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
	faces = face_cascade.detectMultiScale(gray, 1.3, 5)

	for (x,y,w,h) in faces:
		# To draw a rectangle in a face 
		cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2) 
		roi_gray = gray[y:y+h, x:x+w]
		roi_color = img[y:y+h, x:x+w]

	eyes = eye_cascade.detectMultiScale(roi_gray)
	list_ex = []
	list_ey = []
	list_ew = []
	list_eh = []
  
        #To draw a rectangle in eyes
	for (ex,ey,ew,eh) in eyes:
		if ew >= 80 and eh >= 80:
			#cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,127,255),2)
			list_ex.append(ex)
			list_ey.append(ey)
			list_ew.append(ew)
			list_eh.append(eh)

	#rectangle on forhead
	fx = min(list_ex) + list_ew[list_ex.index(min(list_ex))]
	fy = max(list_ey)
	#extra values in x and y in the parameters are adjustements made after manual testing
	cv2.rectangle(roi_color, (fx,fy-150),(fx+100,fy-20),(0,127,255),2)

	imS = cv2.resize(img, (960, 540)) 
	#cv2.imshow('img',imS)
	#cv2.waitKey(0)
	x1 = x + fx
	x2 = x + fx + 100
	y1 = y + fy - 150
	y2 = y + fy - 20

	imRGB = img[y1:y2, x1:x2]
	#cv2.imshow('img',imRGB)
	#cv2.waitKey(0)

	R = []
	G = []
	B = []
	size_list = list(imRGB.shape[:2])
	pixel_values = []
	for i in range(0, size_list[0]):
		for j in range(0, size_list[1]):
			k = imRGB[i,j]
			R.append(k[0])
			G.append(k[1])
			B.append(k[2])
	return R, G, B

def average_and_export():
	i = 0
	count = 0.1
	pixel_values = []
	frames_num = rep_files_init()
	while i < frames_num:
		i += 1
		image = "frames/frame" + str(i) + ".jpg"
		read_img = cv2.imread(image)
		#Bug here inside of func with min funcs of empty data
<<<<<<< HEAD
		try:
			out_colors = RGB_dataframe(read_img, i)
		except:
			out_colors = out_colors
=======
		
		out_colors = RGB_dataframe(read_img, i)
>>>>>>> develop
		Ravg = sum(out_colors[0])/len(out_colors[0])
		Gavg = sum(out_colors[1])/len(out_colors[1])
		Bavg = sum(out_colors[2])/len(out_colors[2])
		pixel_values.append([Ravg, Gavg, Bavg])
		if i/frames_num >= count:
			print(str(round(count*100))+ "% of the database exported to csv")
			count += 0.1
	
	with open('RGB database/RGB_data.csv', 'w', newline="") as f:
		fields = ['R', 'G', 'B'] 
		write = csv.writer(f)
		write.writerow(fields)
		write.writerows(pixel_values)
	return	

average_and_export()