import cv2
import os
import numpy as np

def load_images_from_folder(folder):
    images = []; FNS=[]
    for filename in os.listdir(folder):        
        img = cv2.imread(os.path.join(folder,filename))        
        if img is not None:
            images.append(img); FNS.append(filename)
    return images,FNS

folder='RED1'; 
images,FNS=load_images_from_folder(folder);
FNS2,images2 = zip(*sorted(zip(FNS, images)))
global F,LX,LY,LX2,LY2
LX=images2[0].shape[1]; LY=images2[0].shape[0]
F=8; LX2=int(LX/F); LY2=int(LY/F)
print('FNS=',FNS,' FNS2=',FNS2,' LX,LY,LX2,LY2=',LX,LY,LX2,LY2)

'''
nn=0
for frame in images2: 
    cv2.imshow('frame',frame)
    print(nn,FNS2[nn],frame.shape)
    if(cv2.waitKey(1000) & 0xFF == ord('q')): pass
    nn+=1
'''


def RED_bottom(img):
    img1=np.copy(img)
    img2 = cv2.resize(img1, (LX2,LY2), interpolation=cv2.INTER_AREA)
    Y=LY2-1; XM=int(LX2/2); RED=[]; ra=1.5
    for x in range(LX2):
        if(img2[Y][x][2] > 255*0.2 and img2[Y][x][2] > ra*img2[Y][x][1] 
            and img2[Y][x][2] > ra*img2[Y][x][0]):
            RED.append(x)
    LRED=len(RED)
    if(LRED > 0): 
        MIDL=int(np.median(RED))
        cv2.line(img2,(MIDL,0),(MIDL,Y),(0,255,0),2)
        cv2.line(img1,(MIDL*F,0),(MIDL*F,Y*F),(0,255,0),4)
    else: MIDL=0
    return LRED,MIDL,img1,img2


N=0
for frame in images2: 
    LRED,MIDL,img1,img2=RED_bottom(frame)
    print(N,FNS2[N],'LRED,MIDL=',LRED,MIDL)
    cv2.imshow('img1',img1)
    cv2.imshow('img2',img2)
    if(cv2.waitKey(1000) & 0xFF == ord('q')): pass
    N+=1

