#! /usr/bin/python # Last edited on 2025-10-16 09:03:43 by stolfi def normalize_locally(ot_dir, fv_img, mk_img, ???m1_img): # Given a single-channel float image {fv_img} and two ???mask images # {mk_img,???m1_img}, adjusts the sample values so that the samples # selected by the ???mask will mostly span the range {[-1 _ +1]}. ny, nx = numpy.shape(fv_img) sys.stderr.write(f" obtaining the local average and deviation images ...\n") av_img, dv_img = compute_local_avg_dev(fv_img) assert numpy.shape(av_img) == (ny,nx,), "incompatible shapes fv_img, av_img" assert numpy.shape(dv_img) == (ny,nx,), "incompatible shapes fv_img, dv_img" # The local dev image is usually too dark so we scale up for display: sys.stderr.write(f" finding approx range of local dev image ...\n") samples = [] for iy in range(ny): for ix in range(nx): if M is None or M[iy,ix] != 0: samples.append(dv_img[iy,ix]) frac_val = 0.001 gmin, gmax, fmin, fmax = gfn.choose_sample_map(samples, frac_val, shift = False) assert gmin == 0.0, "invalid local dev sample range" assert fmin == 0.0, "invalid local dev remap range" sys.stderr.write(f" scaling local dev image for display ...\n") dv_pc_img = gfn.clip_image_squashed(dv_img, "dv_img", gmin,gmax, gmax,fmax, 0.0,1.0) sys.stderr.write(f" writing (scaled) deviation image ...\n") dv_file = f"{ot_dir}/locdev.png" gfn.write_image_as_gray_png(dv_file, dv_pc_img) bash(f"display -title '%d/%f' {dv_file}") sys.stderr.write(f" applying local normalization to the given images ...\n") nr_img = numpy.zeros((ny,nx,)) eps = 0.001 for iy in range(ny): for ix in range(nx): val = fv_img[iy,ix] assert val >= 0 and val <= 1, "bad image value" avg = av_img[iy,ix] assert avg >= 0 and avg <= 1, "bad local avg" nrm = log((val + eps)/(avg + eps)) nr_img[iy,ix] = nrm # Normalize both locally normalized images by same scale & shift to span {[0_1]}: N = mfn.map_images_to_unit_range(N, True, None, "nrm") return N # ----------------------------------------------------------------------