Untitled

 avatar
unknown
python
3 years ago
5.1 kB
4
Indexable
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

# import np as np
import OpenEXR
import os
import numbers
import Imath
import cv2
import numpy as np
import pickle
import random

def adjust_gamma(image, gamma=2.2):
	# build a lookup table mapping the pixel values [0, 255] to
	# their adjusted gamma values
	invGamma = 1.0 / gamma
	table = np.array([((i/255 ) ** invGamma) * 255
		for i in np.arange(0, 256)]).astype("uint8")
	# apply gamma correction using the lookup table
	return cv2.LUT(image, table)


onlyfiles=[]
dataset_out ={}
dataset_out_train ={}
dataset_in={}
dataset_in["paths"]=[]

root= "/mnt/CAPOOM_STORAGE/Projects/IbrahimScripts/render/footprintrender/3d/"
count= 0
# for path, subdirs, files in os.walk(root):
#     for name in files:
#         onlyfiles.append(os.path.join(path, name))
# random.shuffle(onlyfiles)
# np.save("onlyfiles.npy",onlyfiles)
# onlyfiles = np.load("onlyfiles.npy")
with open( "/mnt/CAPOOM_STORAGE/Projects/IbrahimScripts/render/footprintrender/footprint.pickle", "rb" ) as f:
    floos = pickle.load( f )
f.close()
# allboxes = floos["boxes"]
onlyfiles = floos["paths"]
for file in onlyfiles[:1]:

    if file.endswith(".exr"):
        # try:
            
            exr = OpenEXR.InputFile(file)
            exr2d = OpenEXR.InputFile(file.replace("3d", "2d"))
            # exrd = OpenEXR.InputFile("/mnt/CAPOOM_STORAGE/Projects/IbrahimScripts/render/footprintrender/3d/009716.exr")
            height = exr2d.header()['displayWindow'].max.y + 1 - exr2d.header()['displayWindow'].min.y
            width = exr2d.header()['displayWindow'].max.x + 1 - exr2d.header()['displayWindow'].min.x
            
            masks = []
            boxes = []
            for i,channel in enumerate(exr2d.header()["channels"]):
                if i >3 and "B" in channel:
                    mask=np.reshape(np.frombuffer(exr2d.channel(channel, Imath.PixelType(Imath.PixelType.FLOAT)), dtype=np.float32), (height, width,1))
                    masks.append(np.squeeze(mask))
                    contours,_ = cv2.findContours(mask.astype("uint8").copy(), 1, 1) # not copying here will throw an error
                    contour = mask.astype("uint8").copy()
                    cv2.drawContours(contour,[contours[0]], 0, (0,0,255), 1)
                    cv2.imshow(contour)
                    peri = cv2.arcLength(contours[0], True)
                    corners = cv2.approxPolyDP(contours[0], 0.04 * peri, True)
                    rect = cv2.minAreaRect(contours[0]) # basically you can feed this rect into your classifier
                    (x,y),(w,h), a = rect
                    box = cv2.boxPoints(rect)
                    box =np.flip(np.int0(box),1) 
                    boxes.append(box)
            masks = np.transpose(np.array(masks),(1,2,0))
            # Zb = np.expand_dims(np.reshape(np.frombuffer(exr.channel("puzzleMatte.B", Imath.PixelType(Imath.PixelType.FLOAT)), dtype=np.float32), (height, width)),axis=2)
            # Zg = np.expand_dims(np.reshape(np.frombuffer(exr.channel("puzzleMatte.G", Imath.PixelType(Imath.PixelType.FLOAT)), dtype=np.float32), (height, width)),axis=2)
            # Zr = np.expand_dims(np.reshape(np.frombuffer(exr.channel("puzzleMatte.R", Imath.PixelType(Imath.PixelType.FLOAT)), dtype=np.float32), (height, width)),axis=2)
            # Z= np.concatenate( (Zb,Zg,Zr),axis=2)
            # Z= cv2.convertScaleAbs(Z, alpha=(255.0))
            image = cv2.imread(file, cv2.IMREAD_UNCHANGED)
            image = cv2.convertScaleAbs(image, alpha=(255.0))
            image=adjust_gamma(image[:,:,:3],2.2)
            if count % 100 ==0:
                print(count)
            # dim= (224,224)
            # resize and transpose image
            # image = cv2.resize(image, dim, interpolation = cv2.INTER_LINEAR).transpose((1,0,2))
            # if "depth" in dataset_in:
            #     dataset_in["depth"].append(Z)
            # else:
            #     dataset_in["depth"] =[ Z]
            # if "image" in dataset_in:
            #     dataset_in["image"].append(image)
            # else:
            #     dataset_in["image"] =[ image]
            # if "name" in dataset_in:
            #     dataset_in["name"].append(file.split("/")[-1])
            # else:
            #     dataset_in["name"] =[ file.split("/")[-1]]
            for key, value in exr.header().items():
                if ('rs/' not in key) and isinstance(value, (int, float,numbers.Integral)) :
                    if key in dataset_out:
                        dataset_out[key].append(value)
                    else:
                        dataset_out[key]= [str(type(value)),value]
            # dataset_out[key] =[ value]
            dataset_in["paths"].append(file)
            count +=1
        except:
            print(file)
print("0")


# picked={"unique":unique,"cls_order":classes,"reg_order":regs,"paths":dataset_in["paths"],"all_keys":all_keys}
pickle.dump( dataset_in, open( "/mnt/CAPOOM_STORAGE/Projects/IbrahimScripts/render/footprintrender/footprint.pickle", "wb" ) )









Editor is loading...