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
def convert_exr_and_write(exr, dest_path, img_format, default_height=400, default_width=900): im = cv2.imread(exr, -1) height, width = im.shape[:2] # convert to jpg if img_format == 'jpg': # tonemap = cv2.createTonemap(gamma=1) # im = tonemap.process(im) # im = im[0:height-600,:] im = cv2.normalize(im, None, alpha=0, beta=20000, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U) im = np.uint16(im) # im = cv2.resize(im, (default_width, default_height)) cv2.imwrite(dest_path, im) elif img_format == 'exr': # convert to exr tonemap = cv2.createTonemap(gamma=1) im = tonemap.process(im) im = im[0:height - 600, :] im = cv2.resize(im, (default_width, default_height)) cv2.imwrite(dest_path, im) else: raise TypeError('Supported format jpg and exr')
def hdr_uint_convert(img, dtype, max_val): """ """ uint_max = np.array(-1, dtype=dtype) # intentional underflow #res_nbit = np.clip(img * max_val, 0, max_val).astype(dtype) tonemap = cv.createTonemap(gamma=1.0) out = tonemap.process(img) return (out * uint_max).astype(dtype)
def test_tonemap(self): global hdrDebevec print("Tonemaping using Gamma and Drago's method ... ") tonemapGamma = cv2.createTonemap(3) tStart = time.time() ldrGamma = tonemapGamma.process(hdrDebevec) tEnd = time.time() tOril = tEnd - tStart tStart = time.time() _tonemap.process(hdrDebevec) tEnd = time.time() tOur = tEnd - tStart print("tOril:", tOril) print("tOur:", tOur) cv_file = cv2.FileStorage("TonemapGamma.ext", cv2.FILE_STORAGE_READ) ldrGamma_our = cv_file.getNode("result").mat() ldrGamma_our[np.isnan(ldrGamma_our)] = 0 self.assertEqual(np.allclose(ldrGamma_our, ldrGamma), True) tonemapDrago = cv2.createTonemapDrago(1.0, 0.7) tStart = time.time() ldrDrago = tonemapDrago.process(hdrDebevec) tEnd = time.time() tOril = tEnd - tStart tStart = time.time() _tonemap.processDrag(hdrDebevec) tEnd = time.time() tOur = tEnd - tStart print("tOril:", tOril) print("tOur:", tOur) cv_file = cv2.FileStorage("TonemapDrag.ext", cv2.FILE_STORAGE_READ) ldrDrag_our = cv_file.getNode("result").mat() ldrDrag_our[np.isnan(ldrDrag_our)] = 0 self.assertEqual(np.allclose(ldrDrag_our, ldrDrago, 1), True) hdrDebevec = 3 * hdrDebevec cv2.imwrite("hdrDebevec.jpg", hdrDebevec * 255) print("saved hdrDebevec.jpg") ldrGamma = 3 * ldrGamma cv2.imwrite("ldrGamma_cv.jpg", ldrGamma * 255) print("saved ldrGamma_cv.jpg") ldrGamma_our = 3 * ldrGamma_our cv2.imwrite("ldrGamma_our.jpg", ldrGamma_our * 255) print("saved ldrGamma_our.jpg") ldrDrag_our = 3 * ldrDrag_our cv2.imwrite("ldrDrag_our.jpg", ldrDrag_our * 255) print("saved ldrDrag_our.jpg") ldrDrago = 3 * ldrDrago cv2.imwrite("ldrDrago.jpg", ldrDrago * 255) print("saved ldrDrago.jpg") # vim: set fenc=utf8 ff=unix et sw=4 ts=4 sts=4:
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
def run(): images, times = loadExposureSeq(settings.BASE_DIR) calibrate = cv.createCalibrateDebevec() response = calibrate.process(images, times) merge_debevec = cv.createMergeDebevec() hdr = merge_debevec.process(images, times, response) tonemap = cv.createTonemap(2.2) ldr = tonemap.process(hdr) merge_mertens = cv.createMergeMertens() fusion = merge_mertens.process(images) out_file_name = 'fusion' + date_time + '.png' OUT_FILE = os.path.join(settings.HDR_ROOT, out_file_name) cv.imwrite(OUT_FILE, fusion * 255)
def mertens_hdr(image_names, contrast=1.0, exposure=0.0, gamma=2.2, saturation=1.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. """ images = read_images(image_names) align_images(images) mertens_img = process_mertens(images, contrast, saturation, exposure) tonemap = cv2.createTonemap(gamma) ldr_mertens = tonemap.process(mertens_img) img_out = get_image_output(image_names[1], output) cv2.imwrite(img_out, ldr_mertens * 255)
def imageFloat(self, gamma): global imagenPrincipal imagenPrincipal = cv2.imread(self.rutaImage) #cargar la imagen cv2.imshow('Principal', imagenPrincipal) setGama = float(gamma) imagenPrincipal = imagenPrincipal.astype(float) gammaY = float(1 / float(setGama)) #I ~ u^y # # visor HDR pixelAlto = np.amax(imagenPrincipal) print('PixelAlto') print(pixelAlto) hdrImagen = np.array(imagenPrincipal, dtype=np.float64) #prepara la imgaen hdr hdrImagen[:, :] = (hdrImagen[:, :].astype(float) / float(pixelAlto)) * (255.0) tonemap1 = cv2.createTonemap(gamma=float(setGama)) #asignado gama # res_debvec = tonemap1.process(imagenPrincipal.copy())#alterando pixel por la gamma res_debvec = tonemap1.process( hdrImagen.copy()) #alterando pixel por la gamma hdrImagen = np.array(hdrImagen, dtype=np.uint8) #refactor a unit8 cv2.imshow("Gamma " + str(setGama), hdrImagen) imagenPrincipal = hdrImagen
print("Working on the HDR image. (takes a few seconds.)") ## [Load images and exposure times] images, times = loadExposureSeq('../Data') ## [Load images and exposure times] ## [Estimate camera response] calibrate = cv.createCalibrateDebevec() response = calibrate.process(images, times) ## [Estimate camera response] ## [Make HDR image] merge_debevec = cv.createMergeDebevec() hdr = merge_debevec.process(images, times, response) ## [Make HDR image] ## [Tonemap HDR image] tonemap = cv.createTonemap(2.2) ldr = tonemap.process(hdr) ## [Tonemap HDR image] ## [Perform exposure fusion] merge_mertens = cv.createMergeMertens() fusion = merge_mertens.process(images) ## [Perform exposure fusion] CombinedImages = cv.hconcat([fusion, hdr]) CombinedImagesAll = cv.hconcat([CombinedImages, ldr]) cv.imshow("Fusion hdr ldr", CombinedImagesAll) cv.waitKey()
print("merged") if args.show_steps: for [(i, j), vv], marker in zip(pixel_values.items(), MARKERS): e = hdr_debevec[i, j, args.color_i] plt.scatter(vv, np.array(log_ts) + np.log(e) + 1.6, marker=marker, label=f'Pixel [{i}, {j}]') plt.plot(np.log(crf_debevec[:, 0, args.color_i]), color=OPEN_CV_COLORS[args.color_i]) plt.tight_layout() plt.legend() plt.show() # Tonemap HDR image tonemap1 = cv2.createTonemap(gamma=2.2) res_debevec = tonemap1.process(hdr_debevec.copy()) x = save_8bit(res_debevec, 'res_debevec.jpg') plt.imshow(x) plt.show() if args.show_steps: merge_robertson = cv2.createMergeRobertson() hdr_robertson = merge_robertson.process(images, times=times_array.copy()) # Tonemap HDR image tonemap1 = cv2.createTonemap(gamma=2.2) res_robertson = tonemap1.process(hdr_robertson) save_8bit(res_robertson, 'res_robertson.jpg') # Exposure fusion using Mertens
cv2.imshow('Principal', imagenPrincipal) setGama = input('Gamma :') # setGamaV=float(1**float(setGama)) imagenPrincipal = imagenPrincipal.astype(float) # imagenPrincipal[:,:]=(float((setGamaV)))*((imagenPrincipal[:,:].astype(float))**(float(setGama))) # # HDR pixelAlto = np.amax(imagenPrincipal) print('PixelAlto') print(pixelAlto) hdrImagen = np.array(imagenPrincipal, dtype=np.float64) #prepara la imgaen hdr hdrImagen[:, :] = (hdrImagen[:, :].astype(float) / float(pixelAlto)) * ( 255.0) #usar clanal de 8 bits tonemap1 = cv2.createTonemap(gamma=float(setGama)) #asignado gama res_debvec = tonemap1.process( imagenPrincipal.copy()) #alterando pixel por la gamma hdrImagen = np.array(hdrImagen, dtype=np.uint8) #refactor a unit8 cv2.imshow("Gamma " + str(setGama), hdrImagen) imagenPrincipal = hdrImagen def grayWorld(): sumaCanalRed = np.sum(imagenPrincipal[:, :, 2]) #obtener suma total, canal rojo sumaCanalGreen = np.sum( imagenPrincipal[:, :, 1]) #obtener suma total, canal verde sumaCanalBlue = np.sum( imagenPrincipal[:, :, 0]) #obterner suma total, canal azul
def convert2png(path, bit, Dataset): if Dataset == 'Funt_et_al': (name, _) = set_name(path) name.remove('S0170') name.remove('S0390') name.remove('S0540') name.remove('S1150') name.remove('S0030') name.remove('S0040') name.remove('S0120') name.remove('S0180') name.remove('S0430') name.remove('S0500') name.remove('S1100') path_hdr = path + '\hdr_cc' flist = glob(path_hdr + '\*.hdr') else: path_img = path + '\png1' flist = glob(path_img + '\*.png') pt = progress_timer(n_iter=len(flist), description='Preparing Color-casted Images :') for i in range(len(flist)): img12 = cv2.imread(flist[i], cv2.IMREAD_UNCHANGED).astype(np.float32) if Dataset == 'Shi_Gehler': if i >= 86: img12 = np.maximum(0., img12 - 129.) clip_percentile = 2.5 img12 = (img12 / (2**bit - 1)) * 100.0 image = convert_to_8bit(img12, clip_percentile) image = (cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) gamma = 1 / 2.2 image = pow(image, gamma) * (255.0 / pow(255, gamma)) img8 = np.array(image, dtype=np.uint8) image8 = (cv2.cvtColor(img8, cv2.COLOR_BGR2RGB)) elif Dataset == 'Funt_et_al': gamma_tone = 2.2 clip_percentile = 0.2 tonemap = cv2.createTonemap(gamma_tone) img12 = tonemap.process(img12) if np.any(np.isnan(img12)): img12[np.isnan(img12)] = 0 image8 = convert_to_8bit(img12, clip_percentile) elif Dataset == 'Canon_600D': img12 = np.maximum(0., img12 - 2048) clip_percentile = 2.5 img12 = (img12 / (2**bit - 1)) * 100.0 image = convert_to_8bit(img12, clip_percentile) image = (cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) gamma = 1 / 2.2 image = pow(image, gamma) * (255.0 / pow(255, gamma)) img8 = np.array(image, dtype=np.uint8) image8 = (cv2.cvtColor(img8, cv2.COLOR_BGR2RGB)) if Dataset == 'Shi_Gehler' or Dataset == 'Canon_600D': save_dir = path_img.replace('png1', 'Converted\\') + "%04d.png" % (i + 1) cv2.imwrite(save_dir, image8) elif Dataset == 'Funt_et_al': img_name = name[i] + "_%04d.png" % (i + 1) save_dir = path_hdr.replace('hdr_cc', 'Converted\\') + img_name cv2.imwrite(save_dir, image8) #cv2.imwrite(save_dir, image8); pt.update() pt.finish()
def WhiteBalanceDataSet(path, bit, Dataset): if Dataset == 'Shi_Gehler': path_gt = path + '\gt' mat = (scipy.io.loadmat(path_gt + '\\real_illum_568.mat', squeeze_me=True, struct_as_record=False)) path_img = path + '\png1' flist = glob(path_img + '\*.png') elif Dataset == 'Funt_et_al': mat = mat_illum(path) name, _ = check_set(path) path_hdr = path + '\hdr_cc' flist = glob(path_hdr + '\*.hdr') elif Dataset == 'Canon_600D': mat = (scipy.io.loadmat(path + '\\Canon600D_gt.mat', squeeze_me=True, struct_as_record=False)) path_img = path + '\png1' flist = glob(path_img + '\*.png') pt = progress_timer(n_iter=len(flist), description='Preparing Groundtruth Images :') for i in range(390, len(flist)): if Dataset == 'Shi_Gehler': img12 = cv2.imread(flist[393], cv2.IMREAD_UNCHANGED).astype(np.float32) if i >= 86: img12 = np.maximum(0., img12 - 129.) Gain_R = float(np.max(mat['real_rgb'][i])) / float( (mat['real_rgb'][i][0])) Gain_G = float(np.max(mat['real_rgb'][i])) / float( (mat['real_rgb'][i][1])) Gain_B = float(np.max(mat['real_rgb'][i])) / float( (mat['real_rgb'][i][2])) image8 = white_balance_image(img12, bit, Gain_R, Gain_G, Gain_B) save_dir = path_img.replace( 'png1', 'GroundTruth_1') + "\%04d.png" % (i + 1) cv2.imwrite(save_dir, image8) i += 1 elif Dataset == 'Funt_et_al': #k = 0; gamma_tone = 2.2 tonemap = cv2.createTonemap(gamma_tone) img12 = cv2.imread(flist[i], cv2.IMREAD_UNCHANGED) avg_R = np.mean(mat[i][:, 0]) avg_G = np.mean(mat[i][:, 1]) avg_B = np.mean(mat[i][:, 2]) Gain_R = float(np.max((avg_R, avg_G, avg_B)) / float(avg_R)) Gain_G = float(np.max((avg_R, avg_G, avg_B)) / float(avg_G)) Gain_B = float(np.max((avg_R, avg_G, avg_B)) / float(avg_B)) img12[:, :, 0] = np.minimum(img12[:, :, 0] * Gain_B, 255) img12[:, :, 1] = np.minimum(img12[:, :, 1] * Gain_G, 255) img12[:, :, 2] = np.minimum(img12[:, :, 2] * Gain_R, 255) image = tonemap.process(img12) clip_percentile = 0.2 if np.any(np.isnan(image)): image[np.isnan(image)] = 0 image = np.clip( image * (255.0 / np.percentile(image, 100 - clip_percentile, keepdims=True)), 0, 255) img_name = name[i] + "_GT_%01d.png" % (i + 1) save_dir = path_hdr.replace('hdr_cc', 'GroundTruth\\') + img_name cv2.imwrite(save_dir, image) # ============================================================================= # while k < 4: # img12 = cv2.imread(flist[i], cv2.IMREAD_UNCHANGED); # Gain_R= float(np.max(mat[i][k]))/float((mat[i][k][0])); # Gain_G= float(np.max(mat[i][k]))/float((mat[i][k][1])); # Gain_B= float(np.max(mat[i][k]))/float((mat[i][k][2])); # # img12[:, :, 0] = np.minimum(img12[:, :, 0] * Gain_B,255); # img12[:, :, 1] = np.minimum(img12[:, :, 1] * Gain_G,255); # img12[:, :, 2] = np.minimum(img12[:, :, 2] * Gain_R,255); # # # image = tonemap.process(img12); # clip_percentile = 0.2; # # if np.any(np.isnan(image)): # image[np.isnan(image)] = 0; # # image = np.clip(image * (255.0 / np.percentile(image, 100 - clip_percentile, keepdims=True)), 0, 255); # # img_name = name[i] + "_GT_%01d.png" % (k+1); # save_dir = path_hdr.replace('hdr_cc', 'GroundTruth\\') + img_name; # cv2.imwrite(save_dir, image); # # k += 1; # # ============================================================================= elif Dataset == 'Canon_600D': img12 = cv2.imread(flist[i], cv2.IMREAD_UNCHANGED).astype(np.float32) img12 = np.maximum(0., img12 - 2048.) Gain_R = float(np.max(mat['groundtruth_illuminants'][i])) / float( (mat['groundtruth_illuminants'][i][0])) Gain_G = float(np.max(mat['groundtruth_illuminants'][i])) / float( (mat['groundtruth_illuminants'][i][1])) Gain_B = float(np.max(mat['groundtruth_illuminants'][i])) / float( (mat['groundtruth_illuminants'][i][2])) image8 = white_balance_image(img12, bit, Gain_R, Gain_G, Gain_B) save_dir = path_img.replace('png1', 'GroundTruth') + "\%04d.png" % (i + 1) cv2.imwrite(save_dir, image8) i += 1 pt.update() pt.finish()
import cv2 import numpy as np Tonemap = None image = None Tonemap = cv2.createTonemap() Tonemap.setGamma(3) image = cv2.imread('media/lena.jpg', 1) cv2.imshow('mywin', Tonemap.process(np.asarray(image, dtype=np.float32))) if cv2.waitKey(0) & 0xff == 27: pass cv2.destroyAllWindows()
def tonemap_exr(img, gamma=2.2): tm = cv2.createTonemap(gamma=gamma) return tm.process(img)
def tonemap(img, gamma=2.2): tm = cv2.createTonemap(gamma=gamma) img_tm = tm.process(img) return np.clip(img_tm * 255, 0, 255).astype('uint8')
import cv2 as cv import numpy as np # Loading exposure images into a list img_fn = ["img0.jpg", "img1.jpg", "img2.jpg", "img3.jpg"] img_list = [cv.imread(fn) for fn in img_fn] exposure_times = np.array([15.0, 2.5, 0.25, 0.0333], dtype=np.float32) # Merge exposures to HDR image merge_debevec = cv.createMergeDebevec() hdr_debevec = merge_debevec.process(img_list, times=exposure_times.copy()) merge_robertson = cv.createMergeRobertson() hdr_robertson = merge_robertson.process(img_list, times=exposure_times.copy()) # Tonemap HDR image tonemap1 = cv.createTonemap(gamma=2.2) res_debevec = tonemap1.process(hdr_debevec.copy()) tonemap2 = cv.createTonemap(gamma=1.3) res_robertson = tonemap2.process(hdr_robertson) # Exposure fusion using Mertens merge_mertens = cv.createMergeMertens() res_mertens = merge_mertens.process(img_list) # Convert datatype to 8-bit and save res_debevec_8bit = np.clip(res_debevec * 255, 0, 255).astype('uint8') res_robertson_8bit = np.clip(res_robertson * 255, 0, 255).astype('uint8') res_mertens_8bit = np.clip(res_mertens * 255, 0, 255).astype('uint8') cv.imwrite("hdr_debevec.jpg", res_debevec_8bit) cv.imwrite("hdr_robertson.jpg", res_robertson_8bit) cv.imwrite("fusion_mertens.jpg", res_mertens_8bit)
hdr_debevec = merge_debevec.process(img_list, times=exposure_times.copy()) merge_robertson = cv.createMergeRobertson() hdr_robertson = merge_robertson.process(img_list, times=exposure_times.copy()) # Tonemap HDR image # We map the 32-bit float HDR data into the range[0..1]. # Actually, in some cases the values can be larger than 1 or lower the 0, # so notice we will later have to clip the data in order to avoid overflow. # # gamma: # positive value for gamma correction. # Gamma value of 1.0 implies no correction, # gamma equal to 2.2f is suitable for most displays. # Generally gamma > 1 brightens the image and gamma < 1 darkens it. tonemap = cv.createTonemap(gamma=2.2) res_debevec = tonemap.process(hdr_debevec.copy()) res_robertson = tonemap.process(hdr_robertson.copy()) # Exposure fusion using Mertens merge_mertens = cv.createMergeMertens() res_mertens = merge_mertens.process(img_list) # Convert datatype to 8-bit and save res_debevec_8bit = np.clip(res_debevec * 255, 0, 255).astype('uint8') res_robertson_8bit = np.clip(res_robertson * 255, 0, 255).astype('uint8') res_mertens_8bit = np.clip(res_mertens * 255, 0, 255).astype('uint8') # results results = [ cv.cvtColor(res, cv.COLOR_BGR2RGB)