Ejemplo n.º 1
0
def part_four(hdr1, hdr2):
    cv2.imwrite('./results/part_four/hdr1_original.png', hdr1)
    cv2.imwrite('./results/part_four/hdr2_original.png', hdr2)

    tonemap1 = cv2.createTonemapReinhard(3.5, -2.0, 0.25, 0.75)
    tonemap2 = cv2.createTonemapReinhard(3.5, 0.0, 0.25, 0.0)

    tonemapHDR1 = tonemap1.process(hdr1)
    tonemapHDR2 = tonemap2.process(hdr2)

    cv2.imwrite('./results/part_four/hdr1_tonemap.png', tonemapHDR1 * 255)
    cv2.imwrite('./results/part_four/hdr2_tonemap.png', tonemapHDR2 * 255)
Ejemplo n.º 2
0
def tMO(file,name): #tonemapping the file
    try:
        if (name == 'reinhard'):
            print('Reinhard')
            intensity=-1.0
            light_adapt=0.8
            color_adapt=0.0
            gamma=2.0
            tmo = cv2.createTonemapReinhard(gamma=gamma, intensity=intensity, light_adapt=light_adapt, color_adapt=color_adapt)
            #([, gamma[, intensity[, light_adapt[, color_adapt]]]]) https://www.kite.com/python/docs/cv2.createTonemapReinhard#
            
        if (name == 'mantiuk'):
            print('Mantiuk')
            saturation=1.0
            scale=0.75
            gamma=2.0
            tmo = cv2.createTonemapMantiuk(saturation=saturation, scale=scale, gamma=gamma)
            
        if (name == 'drago'):
            print('Drago')
            saturation=1.0
            bias=0.85
            gamma=2.0
            tmo = cv2.createTonemapDrago(saturation=saturation, bias=bias, gamma=gamma)
        if (name == 'linear'):
            print('Linear')
            gamma=2.0
            tmo = cv2.createTonemap(gamma=gamma)
    except: 
        print('ToneMapping Error')
    ldr = tmo.process(file)
    return ldr
Ejemplo n.º 3
0
def reinhard(x, intensity=0.0, light_adapt=0.9, color_adapt=0.1, gamma=2.2):
    return cv2.createTonemapReinhard(
        gamma=gamma,
        intensity=intensity,
        light_adapt=light_adapt,
        color_adapt=color_adapt,
    ).process(x)
Ejemplo n.º 4
0
def tonemap(hdr):
    def tmCallback(val):
        pass

    #create user interface w/ tone mapping controls
    cv2.namedWindow("Tone Map", cv2.WINDOW_NORMAL)
    cv2.resizeWindow("Tone Map", 750, 750)
    cv2.imshow("Tone Map", hdr)

    cv2.createTrackbar("Gamma         ", "Tone Map", 0, 4, tmCallback)
    cv2.createTrackbar("Vibrance", "Tone Map", 0, 4, tmCallback)

    finished = False
    while not finished:
        key = cv2.waitKey(0)
        if key == ord('a'):
            finished = True

    #capture trackbar values
    gamma = cv2.getTrackbarPos("Gamma         ", "Tone Map")
    comp = cv2.getTrackbarPos("Vibrance", "Tone Map")

    cv2.destroyAllWindows()
    print("Tone Mapping...")

    # Tonemap using Reinhard's method to obtain 24-bit color image
    tonemap = cv2.createTonemapReinhard(gamma / 4.0, 0, comp / 4.0, 0)
    ldr = tonemap.process(hdr)
    completeName = os.path.join(savePath, "Tonemapped.jpg")
    cv2.imwrite(completeName, ldr * 255)

    return ldr
Ejemplo n.º 5
0
def main():
	img = cv2.imread(IMG_LIST[0])
	shape = img.shape
	width = shape[0]
	height = shape[1]

	imgListB, imgListG, imgListR = loadImgs()
	z_b, z_g, z_r = genCompPixel(imgListB, imgListG, imgListR)

	B = [math.log(e) for e in exposure_times]
	w = [z if z <= 127 else 255 - z for z in range(256)]

	# calculate Camera Response Curve
	L = 50
	crcB = CalCRC(z_b, B, L, w)
	crcG = CalCRC(z_g, B, L, w)
	crcR = CalCRC(z_r, B, L, w)
	blueCurve = np.exp(genRadMap(imgListB, crcB, B, w))
	greenCurve = np.exp(genRadMap(imgListG, crcG, B, w))
	redCurve = np.exp(genRadMap(imgListR, crcR, B, w))
	drawCRC(crcB, crcG, crcR)

	hdr = np.zeros(shape, 'float32')
	hdr[..., 0] = np.reshape(blueCurve, (width, height))
	hdr[..., 1] = np.reshape(greenCurve, (width, height))
	hdr[..., 2] = np.reshape(redCurve, (width, height))

	cv2.imwrite('out.hdr', hdr)
	normalize = lambda zi: (zi - zi.min() / zi.max() - zi.min())
	ldr = normalize(np.log(hdr))
	cv2.imwrite('hdr_image.jpg', (ldr/ldr.max())*255)
	tonemapReinhard = cv2.createTonemapReinhard(1.5, 3, 0.5, 0.5)
	ldrReinhard = tonemapReinhard.process(hdr)
	cv2.imwrite("ldr-Reinhard.jpg", ldrReinhard * 255)
Ejemplo n.º 6
0
def process_photos(folders):
    psave = folders["psave"]
    ptmp = folders["ptmp"]
    pgal = folders["pgal"]

    foldername = folders["foldername"]

    save_folder = psave + "/" + foldername
    makedirs(save_folder)

    onlyfiles = [f for f in listdir(ptmp) if isfile(join(ptmp, f))]

    images = []
    times = np.array([], dtype=np.float32)
    logging.info("Loading images for HDR")
    for filename in onlyfiles:
        filesrc = ptmp + "/" + filename
        filedest = save_folder + "/" + filename
        shutil.move(filesrc, filedest)

        file_data = open(filedest, 'rb')
        tags = exifread.process_file(file_data)
        exposure = float(tags['EXIF ExposureTime'].values[0])

        im = cv2.imread(filedest)
        images.append(im)
        times = np.append(times, np.float32(exposure))

    logging.info("Align input images")
    align_MTB = cv2.createAlignMTB()
    align_MTB.process(images, images)

    logging.info('Obtain Camera Response Function (CRF)')
    calibrate_debevec = cv2.createCalibrateDebevec()
    response_debevec = calibrate_debevec.process(images, times)

    logging.info('Merge images into an HDR linear image')
    merge_debevec = cv2.createMergeDebevec()
    hdr_debevec = merge_debevec.process(images, times, response_debevec)

    logging.info('Save HDR image')
    save_file = pgal + "/" + foldername 
    cv2.imwrite(save_file + ".hdr", hdr_debevec)

    logging.info("Tonemaping using Drago's method ... ")
    tonemap_drago = cv2.createTonemapDrago(1.0, 0.7)
    ldr_drago = tonemap_drago.process(hdr_debevec)
    ldr_drago = 3 * ldr_drago
    cv2.imwrite(save_file + "_drago.jpg", ldr_drago * 255)
    
    logging.info("Tonemaping using Reinhard's method ... ")
    tonemap_reinhard = cv2.createTonemapReinhard(1.5, 0,0,0)
    ldr_reinhard = tonemap_reinhard.process(hdr_debevec)
    cv2.imwrite(save_file + "_reinhard.jpg", ldr_reinhard * 255)
    
    logging.info("Tonemaping using Mantiuk's method ... ")
    tonemap_mantiuk = cv2.createTonemapMantiuk(2.2,0.85, 1.2)
    ldr_mantiuk = tonemap_mantiuk.process(hdr_debevec)
    ldr_mantiuk = 3 * ldr_mantiuk
    cv2.imwrite(save_file + "_mantiuk.jpg", ldr_mantiuk * 255)
Ejemplo n.º 7
0
 def __init__(self, ip_pi):
     QThread.__init__(self)
     self.threadID = 1
     self.name = "ImgThread"
     self.window = None
     self.saveOn = False
     self.mergeMertens = cv2.createMergeMertens(1., 1., 1.)
     self.mergeDebevec = cv2.createMergeDebevec()
     self.toneMap = cv2.createTonemapReinhard()
     #        self.claheProc = cv2.createCLAHE(clipLimit=1, tileGridSize=(8,8))
     #        self.simpleWB = cv2.xphoto.createSimpleWB()
     #        self.simpleWB = cv2.xphoto.createGrayworldWB()
     #        self.wb= False
     #         self.equalize = False
     #         self.clahe = False
     #        self.clipLimit = 1.
     self.reduceFactor = 1
     self.ip_pi = ip_pi
     self.hflip = False
     self.vflip = False
     self.table = None
     self.doCalibrate = False
     try:
         npz = np.load("calibrate.npz")
         self.table = npz['table']
     except Exception as e:
         pass
Ejemplo n.º 8
0
def tonemapping(hdr, tmo_func='reinhard', gamma=2.2, fstop=0):
    ## tone mapping hdr
    if tmo_func == 'reinhard':
        tmo = cv2.createTonemapReinhard(gamma=gamma)
    elif tmo_func == 'durand':
        tmo = cv2.createTonemapDurand(gamma=gamma)
    elif tmo_func == 'drago':
        tmo = cv2.createTonemapDrago(gamma=gamma)
    elif tmo_func == 'mantiuk':
        tmo = cv2.createTonemapMantiuk(gamma=gamma)
    elif tmo_func == 'linear':
        output = hdr - hdr.min()
        output = output / output.max()

        # return output
        return tonemapping(output, tmo_func='gamma')
    elif tmo_func == 'gamma':
        inv_gamma = 1.0 / gamma
        exposure = np.power(2., fstop)
        output = clamp_img(np.power(exposure * hdr, inv_gamma), 0, 1)
        return output
    else:
        raise NotImplementedError
    # elif tmo_func =='cut_high':
    #     output = hdr - hdr.min()
    #     output = output/output.max()
    #     return output
    output = tmo.process(hdr.astype('float32'))
    return output
Ejemplo n.º 9
0
def main():
    scene = "./images/scene1/"
    bgImage = cv2.imread(scene + "bg.png", cv2.IMREAD_COLOR)
    obj = cv2.imread(scene + "obj1.png", cv2.IMREAD_UNCHANGED)
    objQuant = quantize(obj[:, :, 0:3], 4)
    objQuant = cv2.cvtColor(objQuant, cv2.COLOR_RGB2RGBA)
    objQuant[:, :, 3] = obj[:, :, 3]

    out = mergeImages(bgImage, objQuant, 0.75)

    obj = cv2.imread(scene + "obj2.png", cv2.IMREAD_UNCHANGED)
    objQuant = quantize(obj[:, :, 0:3], 4)
    objQuant = cv2.cvtColor(objQuant, cv2.COLOR_RGB2RGBA)
    objQuant[:, :, 3] = obj[:, :, 3]

    out = mergeImages(out, objQuant, 0.75)

    cv2.imshow('Merge quantized', out)
    cv2.imwrite(scene + 'scene1answer.png', out)
    debevec = cv2.createMergeDebevec()
    merged = debevec.process([bgImage, out],
                             np.array([0.15, 0.15], dtype=np.float32))

    tonemapper = cv2.createTonemapReinhard(
        0.5, 0, 0, 0)  #Gamma, intensity, light_adapt, color_adapt
    tonemapped = tonemapper.process(merged)
    cv2.imshow("Merge and mapped reinhard quantized", tonemapped)
    out = cv2.convertScaleAbs(tonemapped, alpha=(255.0))
    out = out.astype('uint8')
    cv2.imwrite(scene + 'scene1.png', out)
Ejemplo n.º 10
0
def run(config, model):
    SDR = get_test_data(config.test_path)
    print(SDR.shape)
    rs = model.predict(SDR)
    out = rs[0]
    tonemap = cv2.createTonemapReinhard()
    out = tonemap.process(out.copy())
    cv2.imwrite(os.path.join(config.test_path, 'hdr.jpg'), np.uint8(out * 255))
Ejemplo n.º 11
0
def calc_scene_hdr_psnr():
    scenes_obj = parse_json_file(args.scene_map_fp)

    scenes_psnr = {}

    for i, scene in enumerate(scenes_obj):
        scene_fd = os.path.dirname(scene['ldr_fps'][0])

        scene_rend_fp = scene['rend_fp']
        scene_cv_fp = os.path.join(scene_fd,
                                   '{}_cv-hdr.jpg'.format(scene['ldr_fd']))
        # scene_ldr_fps = scene['ldr_fps']
        scene_exptime_fp = get_scene_exptime_fp(scene_fd)

        print('Processing: ' + scene_fd)

        print('  scene_rend_fp (r): ' + scene_rend_fp)
        rend_hdr_img = cv2.imread(scene_rend_fp)

        # Render HDR image using OpenCV
        if args.force or not os.path.isfile(scene_cv_fp):
            print('  scene_cv_fp (w): ' + scene_cv_fp)
            ldr_imgs = []
            ldr_exptimes = []
            with open(scene_exptime_fp, 'r') as exptimes_file:
                for line in exptimes_file:
                    vals = line.split(',')
                    ldr_imgs.append(
                        cv2.imread(
                            os.path.join(scene_fd, vals[0].split('/')[-1])))
                    ldr_exptimes.append(float(vals[1]))

            ldr_exptimes = np.array(ldr_exptimes, dtype=np.float32)

            # Estimate Camera response function, merge exposures
            calib_debevec = cv2.createCalibrateDebevec()
            resp_debevec = calib_debevec.process(ldr_imgs, ldr_exptimes)
            merge_debevec = cv2.createMergeDebevec()
            hdr_debevec = merge_debevec.process(ldr_imgs, ldr_exptimes,
                                                resp_debevec)

            # Tone mapping
            tone_map = cv2.createTonemapReinhard(1.5, 0, 0, 0)
            cv_hdr_img = tone_map.process(hdr_debevec)
            cv2.imwrite(scene_cv_fp, cv_hdr_img * 255.0)
        else:
            print('  scene_cv_fp (r): ' + scene_cv_fp)
            cv_hdr_img = cv2.imread(scene_cv_fp)

        # Calculate PSNR
        cv_hdr_img = cv2.resize(cv_hdr_img,
                                dsize=(rend_hdr_img.shape[1],
                                       rend_hdr_img.shape[0]),
                                interpolation=cv2.INTER_CUBIC)
        scene_rend_fn = scene_rend_fp.split('/')[-1]
        scenes_psnr[scene_rend_fn] = img_psnr(cv_hdr_img, rend_hdr_img)

    return scenes_psnr
Ejemplo n.º 12
0
def show(filename, fileID):

    # Get Raw Data
    img = merge_raw(filename, 540, 960)
    scale = np.max(img)

    s = downsample(img)

    # Tone-Mapping
    tonemap_night = cv2.createTonemapReinhard(1, -4, 0.7, 0.7)
    ldrh = tonemap_night.process((np.float32(s / scale)))

    # Denoising
    ldrh = cv2.fastNlMeansDenoisingColored((ldrh * 255).astype(np.uint8),
                                           searchWindowSize=15,
                                           templateWindowSize=3,
                                           h=1) / 255

    # Adjust White Balance
    ldrh = grey_world(ldrh)
    output = ldrh

    # Bi-linear Demosaicing
    sd = debayer(img)

    # Tone-Mapping
    tonemap_night = cv2.createTonemapReinhard(1, -4, 0.7, 0.7)
    ldrh = tonemap_night.process((np.float32(sd / scale)))

    # Adjust White Balance
    ldrh = grey_world(ldrh)

    output = np.concatenate(
        (cv2.resize(output, (output.shape[1] * 2, output.shape[0] * 2)), ldrh),
        axis=0)

    cv2.imwrite('{}/output_{}.png'.format(TARGET_DIRECTORY, fileID),
                output[..., ::-1] * 255)
def tMO(file,name): #tonemapping the file
    try:
        if (name == 'reinhard'):
            tom = cv2.createTonemapReinhard()
        if (name == 'mantiuk'):
            tom = cv2.createTonemapMantiuk()
        if (name == 'drago'):
            tom = cv2.createTonemapDrago()
        if (name == 'linear'):
            tom = cv2.createTonemap()
    except: 
        print('ToneMapping Error')
    ldr = tom.process(file)
    return ldr
Ejemplo n.º 14
0
def tone_map(img, tmo_name):
    if (tmo_name == 'exposure'):
        tmo = Exposure(gamma=opt.gamma, stops=opt.stops)
    if (tmo_name == 'reinhard'):
        tmo = cv2.createTonemapReinhard(intensity=-1.0, 
                                        light_adapt=0.8, color_adapt=0.0)
    elif tmo_name == 'mantiuk':
        tmo = cv2.createTonemapMantiuk(saturation=1.0, scale=0.75)
    elif tmo_name == 'drago':
        tmo = cv2.createTonemapDrago(saturation=1.0, bias=0.85)
    elif tmo_name == 'durand':
        tmo = cv2.createTonemapDurand(contrast=3, saturation=1.0, 
                                      sigma_space=8, sigma_color=0.4)
    return tmo.process(img)
Ejemplo n.º 15
0
 def __init__(self,
              intensity=-1.0,
              light_adapt=0.8,
              color_adapt=0.0,
              gamma=2.0,
              randomize=False):
     if randomize:
         gamma = uniform(1.8, 2.2)
         intensity = uniform(-1.0, 1.0)
         light_adapt = uniform(0.8, 1.0)
         color_adapt = uniform(0.0, 0.2)
     self.op = cv2.createTonemapReinhard(
         gamma=gamma,
         intensity=intensity,
         light_adapt=light_adapt,
         color_adapt=color_adapt)
Ejemplo n.º 16
0
def main():
    #读取多张曝光的图像
    images,times = readImagesAndTimes()

    #对齐图像
    alignMTB = cv2.createAlignMTB()
    alignMTB.process(images, images)

    #恢复相机响应函数
    calibrateDebevec = cv2.createCalibrateDebevec()
    responseDebevec = calibrateDebevec.process(images, times)

    # 将多张图像融合成hdr
    mergeDebevec = cv2.createMergeDebevec()
    hdrDebevec = mergeDebevec.process(images, times, responseDebevec)
    # 保存融合结果,可用ps打开
    cv2.imwrite("hdrDebevec.hdr", hdrDebevec)

    # Tonemap using Drago's method to obtain 24-bit color image
    tonemapDrago = cv2.createTonemapDrago(1.0, 0.7)
    ldrDrago = tonemapDrago.process(hdrDebevec)
    ldrDrago = 3 * ldrDrago
    cv2.imwrite("ldr-Drago.jpg", ldrDrago * 255)

    # Tonemap using Durand's method obtain 24-bit color image
    tonemapDurand = cv2.createTonemapDurand(1.5,4,1.0,1,1)
    ldrDurand = tonemapDurand.process(hdrDebevec)
    ldrDurand = 3 * ldrDurand
    cv2.imwrite("ldr-Durand.jpg", ldrDurand * 255)

    # Tonemap using Reinhard's method to obtain 24-bit color image
    tonemapReinhard = cv2.createTonemapReinhard(1.5, 0,0,0)
    ldrReinhard = tonemapReinhard.process(hdrDebevec)
    cv2.imwrite("ldr-Reinhard.jpg", ldrReinhard * 255)

    # Tonemap using Mantiuk's method to obtain 24-bit color image
    tonemapMantiuk = cv2.createTonemapMantiuk(2.2,0.85, 1.2)
    ldrMantiuk = tonemapMantiuk.process(hdrDebevec)
    ldrMantiuk = 3 * ldrMantiuk
    cv2.imwrite("ldr-Mantiuk.jpg", ldrMantiuk * 255)
Ejemplo n.º 17
0
def tone_mapping_Reinhard(img_file,
                          gamma = 1.5,       
                          intensity = 0,       
                          light_adapt = 0,     
                          color_adapt = 0):
            
    '''
    tonemapDrago = cv2.createTonemapDrago(2, 2)
    ldrDrago = tonemapDrago.process(image_output)
    ldrDrago = 3 * ldrDrago
    ldrDrago = ldrDrago * 256.0 - 0.5

    tonemapDurand = cv2.createTonemapDurand(8,4,1.0,1,1)
    ldrDurand = tonemapDurand.process(image_output)
    ldrDurand = 3 * ldrDurand

    tonemapMantiuk = cv2.createTonemapMantiuk(2.2,0.85, 1.2)
    ldrMantiuk = tonemapMantiuk.process(image_output)
    ldrMantiuk = 3 * ldrMantiuk
    '''
    img = imread(img_file).astype(np.float32)/255
    tonemapReinhard = cv2.createTonemapReinhard(gamma,       
                                                intensity,       # [-8, 8]
                                                light_adapt,     # [0, 1]
                                                color_adapt)     # [0, 1]
    
    init_time = time.time()
    ldrReinhard = tonemapReinhard.process(img)
    ldrReinhard = ldrReinhard * 255.0
    np.putmask(ldrReinhard, ldrReinhard > 255, 255)
    np.putmask(ldrReinhard, ldrReinhard < 0, 0)
    ldrReinhard = ldrReinhard.astype(np.uint8)
    print("passed time = {}".format(time.time()-init_time))

    
    plt.figure(figsize = (10,10))
    plt.imshow(ldrReinhard)
    misc.imsave("G:\\ECE516\\HDR team\\Reinhard.jpg",ldrReinhard)
    plt.show()
Ejemplo n.º 18
0
    def __init__(self, ip_pi):
        QThread.__init__(self)
        self.threadID = 1
        self.name = "ImgThread"
        self.window = None
        self.saveOn = False
        self.mergeMertens = cv2.createMergeMertens(1,1,1)
#*        self.mergeMertens = cv2.createMergeMertens()
#         print("Contrast:",self.mergeMertens.getContrastWeight())
#         print("Saturation:",self.mergeMertens.getSaturationWeight())
#         print("Exposure:",self.mergeMertens.getExposureWeight())
        self.mergeDebevec = cv2.createMergeDebevec()
        self.calibrateDebevec = cv2.createCalibrateDebevec()
        self.toneMap = cv2.createTonemapReinhard()
#        self.claheProc = cv2.createCLAHE(clipLimit=1, tileGridSize=(8,8))
#        self.simpleWB = cv2.xphoto.createSimpleWB()
#        self.simpleWB = cv2.xphoto.createGrayworldWB()
#        self.wb= False
#         self.equalize = False
#         self.clahe = False
#        self.clipLimit = 1.
        self.invgamma = np.empty((1,256), np.uint8)
        for i in range(256):
            self.invgamma[0,i] = np.clip(pow(i / 255.0, 0.45) * 255.0, 0, 255)
        self.gamma = np.empty((1,256), np.uint8)
        for i in range(256):
            self.gamma[0,i] = np.clip(pow(i / 255.0, 2.2) * 255.0, 0, 255)
        self.reduceFactor = 1;
        self.ip_pi = ip_pi
        self.hflip = False
        self.vflip = False
        self.table=None
        self.doCalibrate = False
        try:
            npz = np.load("calibrate.npz")
            self.table = npz['table']
        except Exception as e:
            pass
Ejemplo n.º 19
0
def reinhard_hdr(image_names,
                 algo='debevec',
                 exposures=None,
                 gamma=1.0,
                 intensity=0.0,
                 light_adapt=1.0,
                 color_adapt=0.0,
                 output=None):
    """
    Create an HDR image from the supplied images.

    :param images: List of images to process.
    :return: Returns name of new HDR image.
    """
    hdr_img = process_image(image_names, exposures, algo)

    tonemap_reinhard = cv2.createTonemapReinhard(
        gamma, intensity, light_adapt, color_adapt
    )
    ldr_reinhard = tonemap_reinhard.process(hdr_img)

    img_out = get_image_output(image_names[1], output)
    cv2.imwrite(img_out, ldr_reinhard * 255)
Ejemplo n.º 20
0
def main():
    # input multiple exposure images
    folderNM = './img/europe/'
    fileNM = ["low.jpg", "middle.jpg", "high.jpg"]
    imgs = [cv2.imread(folderNM + fn) for fn in fileNM]

    # auto discover exposure time from Exif information of input image file
    exposureTimes = np.array([getExifInfo(folderNM + fn) for fn in fileNM],
                             dtype=np.float32)
    # if Exif information is None, you should set exposure time manually
    # exposureTimes = np.array([15.0, 2.5, 0.25, 0.0333], dtype=np.float32)

    # Estimate camera response function (CRF)
    mergeDebevec = cv2.createMergeDebevec()
    hdr = mergeDebevec.process(imgs, times=exposureTimes.copy())
    hdr[hdr < 0] = 0

    cv2.imwrite("res/hdrDebevec.hdr", hdr)

    # linear
    res1 = 255 * hdr / hdr.max()
    # gamma
    res2 = 255 * (hdr / hdr.max())**0.2

    # reinhardTM_global
    tonemap = cv2.createTonemapReinhard(gamma=1.5)
    res3 = tonemap.process(hdr.copy())
    res3 = percentileCut(res3, 0.5, 99.9) * 255

    cv2.imshow('result_linear', res1.astype(np.uint8))
    cv2.imshow('result_gamma', res2.astype(np.uint8))
    cv2.imshow('result_reinhard', res3.astype(np.uint8))
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    cv2.imwrite("res/tonemappedImg.png", res3)
Ejemplo n.º 21
0
    def createHDR(self):
        """ Numpy array of exposure times from exif data """
        for image in self.image_paths:
            p = Photo(image)
            self.exposure_times.append(p.exifData())
        times_np = np.asarray(self.exposure_times, dtype=np.float32)

        # Align Images
        alignMTB = cv.createAlignMTB()
        alignMTB.process(self.im_list, self.im_list)

        # Find Camera Response Curve
        calibrateDebevec = cv.createCalibrateDebevec()
        responseDebevec = calibrateDebevec.process(self.im_list, times_np)

        # Merge Images
        mergeDebevec = cv.createMergeDebevec()
        hdrDebevec = mergeDebevec.process(self.im_list, times_np,
                                          responseDebevec)
        # Generate HDR image and LDR tone mapped preview
        cv.imwrite("hdr.hdr", hdrDebevec)
        toneMapReinhard = cv.createTonemapReinhard(1.5, 0.0)
        ldrReinhard = toneMapReinhard.process(hdrDebevec)
        cv.imwrite("hdr_preview.jpg", ldrReinhard * 255)
Ejemplo n.º 22
0
def HDR_TMO_Reinhard(fn, g):
    hdr_image = cv.imread(fn, cv.IMREAD_ANYDEPTH)
    tonemap = cv.createTonemapReinhard(gamma=g)
    result = tonemap.process(hdr_image.copy())
    result_8bit = np.clip(result * 255, 0, 255).astype('uint8')
    cv.imwrite("img/TMO_Reinhard.jpg", result_8bit)
def reinhard(hdr):
    tonemap = cv2.createTonemapReinhard()
    ldr = tonemap.process(hdr)
    cv2.imwrite('{}.png'.format('reinhard.png'), ldr * 255)
            raw = rawpy.imread(in_path)
            input_images[str(ratio)[0:2]][ind] = np.expand_dims(pack_raw(raw),
                                                                axis=0) * ratio

            print(gt_path)
            '''
			# method 1: read raw hdr file in rgbe format
			gt_file = open(gt_path, 'rb')
			header = gt_file.read(78)
			gt_bytes = gt_file.read()
			gt_file.close()
			gt_images[ind] = np.expand_dims(np.float32(pack_hdr(gt_bytes)/255.0),axis = 0)# 8-bit, 4 channels
			'''
            # method 2: use Reinhard tonemapped image as gt
            hdr = cv2.imread(gt_path, -1)
            tonemapReinhard = cv2.createTonemapReinhard(3.0, -2.5, 0, 0)
            gt_images[ind] = np.expand_dims(tonemapReinhard.process(hdr),
                                            axis=0)
        #crop
        H = input_images[str(ratio)[0:2]][ind].shape[1]
        W = input_images[str(ratio)[0:2]][ind].shape[2]

        xx = np.random.randint(0, W - ps)
        yy = np.random.randint(0, H - ps)
        input_patch = input_images[str(ratio)[0:2]][ind][:, yy:yy + ps,
                                                         xx:xx + ps, :]
        gt_patch = gt_images[ind][:, yy * 2:yy * 2 + ps * 2,
                                  xx * 2:xx * 2 + ps * 2, :]

        if np.random.randint(2, size=1)[0] == 1:  # random flip
            input_patch = np.flip(input_patch, axis=1)
Ejemplo n.º 25
0
# tonemap all .npy images in current dir to .jpg using OpenCV Reinhard method
import os
import cv2
import numpy as np

for f in os.listdir(os.getcwd()):
    if f.endswith('.npy'):
        hdr = np.load(f)
        hdr = hdr.astype('float32')
        hdr = (hdr - np.min(hdr)) / (np.max(hdr) - np.min(hdr))
        grayscale = True
        if hdr.ndim == 3:
            if hdr.shape[2] == 3:
                # RGB image (H, W, 3)
                hdr = cv2.cvtColor(hdr, cv2.COLOR_RGB2BGR)
                grayscale = False
            elif hdr.shape[2] == 1:
                # grayscale image (H, W, 1)
                hdr = hdr[:, :, 0]
        if grayscale:
            hdr = np.stack([hdr, hdr, hdr], axis=2)

        tmo = cv2.createTonemapReinhard(intensity=-1.0,
                                        light_adapt=0.8,
                                        color_adapt=0.0)
        tonemapped = tmo.process(hdr)
        f_ = f.split('.')[0] + '.jpg'
        cv2.imwrite(f_, tonemapped * 255)
Ejemplo n.º 26
0
def tone_map(stack):
    stack = np.array(stack).squeeze(0).transpose(1, 2, 0)
    # Tonemap using Reinhard's method to obtain 24-bit color image
    tonemapReinhard = cv2.createTonemapReinhard(1.5, 0, 0, 0)
    ldrReinhard = tonemapReinhard.process(stack.copy())
    return (ldrReinhard * 255).clip(0, 255).astype('uint8')
Ejemplo n.º 27
0
def tone_mapping_reinhard():
    tonemapReinhard = cv2.createTonemapReinhard(1.5, 0, 0, 0)
    ldrReinhard = tonemapReinhard.process(hdrDebevec)
    return ldrReinhard * 255
Ejemplo n.º 28
0
def TonemapReinhard(file_path):
    im = cv2.imread(file_path, cv2.IMREAD_ANYDEPTH)
    tonemapReinhard = cv2.createTonemapReinhard(1.5, 0, 0, 0)
    ldrReinhard = tonemapReinhard.process(im)

    return ldrReinhard
Ejemplo n.º 29
0
        # Convert to gray and get the mean value
        Gray = cv2.cvtColor(Raw, cv2.COLOR_BayerBG2GRAY)
        MeanGray = cv2.mean(Gray)

        # White balance
        WB = MeanGray[0] / MeanRGB
        B = HRGB[:, :, 0] * WB[0]
        G = HRGB[:, :, 1] * WB[1]
        R = HRGB[:, :, 2] * WB[2]
        HRGBwb = cv2.merge((B, G, R))

        # Generate the tonemap image
        #ToneMap = cv2.createTonemapReinhard(gamma=0.8, intensity=+3, light_adapt=0.7)
        ToneMap = cv2.createTonemapReinhard(gamma=0.7,
                                            intensity=+3,
                                            light_adapt=0.6)
        ToneHRGBwb = ToneMap.process(np.float32(HRGBwb))
        RGB = np.clip(ToneHRGBwb * 255, 0, 255).astype('uint8')

        # Apply a Contrast Limited Adaptive Histogram Equalization (CLAHE)
        clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
        Bc = clahe.apply(RGB[:, :, 0])
        Gc = clahe.apply(RGB[:, :, 1])
        Rc = clahe.apply(RGB[:, :, 2])
        RGBc = cv2.merge((Bc, Gc, Rc))

        # Save image as JPEG
        cv2.imwrite(x + '.jpeg', RGBc)

        # Display image
    cv2.imwrite("./images/HDR/ldr-Drago-example.jpg", ldrDrago * 255)
    cv2.imshow("ldr-Drago", ldrDrago)
    print("saved ldr-Drago.jpg")

    # Tonemap using Durand's method obtain 24-bit color image
    print("Tonemaping using Durand's method ... ")
    tonemapDurand = cv2.createTonemapDurand(1.5, 4, 1.0, 1, 1)
    ldrDurand = tonemapDurand.process(hdrDebevec)
    ldrDurand = 3 * ldrDurand
    cv2.imwrite("./images/HDR/ldr-Durand-example.jpg", ldrDurand * 255)
    cv2.imshow("ldrDurand", ldrDurand)
    print("saved ldr-Durand.jpg")

    # Tonemap using Reinhard's method to obtain 24-bit color image
    print("Tonemaping using Reinhard's method ... ")
    tonemapReinhard = cv2.createTonemapReinhard(1.5, 0, 0, 0)
    ldrReinhard = tonemapReinhard.process(hdrDebevec)
    cv2.imwrite("./images/HDR/ldr-Reinhard-example.jpg", ldrReinhard * 255)
    cv2.imshow("ldrReinhard", ldrReinhard)
    print("saved ldr-Reinhard.jpg")

    # Tonemap using Mantiuk's method to obtain 24-bit color image
    print("Tonemaping using Mantiuk's method ... ")
    tonemapMantiuk = cv2.createTonemapMantiuk(2.2, 0.85, 1.2)
    ldrMantiuk = tonemapMantiuk.process(hdrDebevec)
    ldrMantiuk = 3 * ldrMantiuk
    cv2.imwrite("./images/HDR/ldr-Mantiuk-example.jpg", ldrMantiuk * 255)
    cv2.imshow("ldrMantiuk", ldrMantiuk)
    print("saved ldr-Mantiuk.jpg")

    # Wait until a key pressed
Ejemplo n.º 31
0
  print("Tonemaping using Drago's method ... ")
  tonemapDrago = cv2.createTonemapDrago(1.0, 0.7)
  ldrDrago = tonemapDrago.process(hdrDebevec)
  ldrDrago = 3 * ldrDrago
  cv2.imwrite("ldr-Drago.jpg", ldrDrago * 255)
  print("saved ldr-Drago.jpg")
  
  # Tonemap using Durand's method obtain 24-bit color image
  print("Tonemaping using Durand's method ... ")
  tonemapDurand = cv2.createTonemapDurand(1.5,4,1.0,1,1)
  ldrDurand = tonemapDurand.process(hdrDebevec)
  ldrDurand = 3 * ldrDurand
  cv2.imwrite("ldr-Durand.jpg", ldrDurand * 255)
  print("saved ldr-Durand.jpg")
  
  # Tonemap using Reinhard's method to obtain 24-bit color image
  print("Tonemaping using Reinhard's method ... ")
  tonemapReinhard = cv2.createTonemapReinhard(1.5, 0,0,0)
  ldrReinhard = tonemapReinhard.process(hdrDebevec)
  cv2.imwrite("ldr-Reinhard.jpg", ldrReinhard * 255)
  print("saved ldr-Reinhard.jpg")
  
  # Tonemap using Mantiuk's method to obtain 24-bit color image
  print("Tonemaping using Mantiuk's method ... ")
  tonemapMantiuk = cv2.createTonemapMantiuk(2.2,0.85, 1.2)
  ldrMantiuk = tonemapMantiuk.process(hdrDebevec)
  ldrMantiuk = 3 * ldrMantiuk
  cv2.imwrite("ldr-Mantiuk.jpg", ldrMantiuk * 255)
  print("saved ldr-Mantiuk.jpg")