import os

from PIL import Image, ImageFilter, ImageMath
from scipy import ndimage
import numpy as np

JPGDIR = '/media/nfs/SRS/IMPAX/'

def img_frombytes(data):
    size = data.shape[::-1]
    databytes = np.packbits(data, axis=1)
    return Image.frombytes(mode='1', size=size, data=databytes)

for pid in sorted(os.listdir(JPGDIR)):
    PATDIR = os.path.join(JPGDIR, pid)
    for study in sorted(os.listdir(PATDIR)):
        if study.endswith('_100'):
            ST100_DIR =  os.path.join(PATDIR, study)
            for jpg in sorted(os.listdir(ST100_DIR)):
                jpg_path = os.path.join(ST100_DIR, jpg)
                img = Image.open(jpg_path).convert('L')
                jpg_ndarray = np.array(img)
                # CC = (0xCB <= jpg_ndarray <= 0xCD)
                CC = np.logical_and(jpg_ndarray >= 0xCB, jpg_ndarray <= 0xCD)
                C0 = (jpg_ndarray <= 0x01)

                MASK = np.logical_or(CC, C0)
                MASK = np.roll(MASK, -1, 0)
                MASK = np.roll(MASK, -1, 1)

                # MASKED = np.logical_and(CC, MASK).astype('uint8') * 255
                MASKED = np.logical_and(CC, MASK).astype('uint8')
                FILTERD = ndimage.rank_filter(MASKED, rank=-2, size=3)
                FILTERD = np.minimum(MASKED, FILTERD)

                # im = Image.fromarray(FILTERD )
                im = img_frombytes(FILTERD)
                im.save ('/shares/Public/0/0.png')


                # print(CC)
                # print(CC.shape)

                # im = img_frombytes(FINAL)
                # imr = im.filter(ImageFilter.RankFilter(3, 3*3-2))
                # out = ImageMath.eval("min(a, b)", a=im, b=imr)
                # out.save ('/shares/Public/0/0.png')
                # img.save ('/shares/Public/0/0.png')

                exit()