Commit f52eb10f authored by Sparkf's avatar Sparkf 🏙️
Browse files

lab3

parent e4d47670
Loading
Loading
Loading
Loading
(208 KiB)

File changed.

No diff preview for this file type.

(41.2 KiB)

File changed.

No diff preview for this file type.

lab3/hist_equ.py

0 → 100644
+97 −0
Original line number Diff line number Diff line
#https://medium.com/hackernoon/histogram-equalization-in-python-from-scratch-ebb9c8aa3f23


import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

def hist_arr(img_flat, bins):
    histogram = np.zeros(bins)
    for i in img_flat:
        histogram[i] += 1
    return histogram




def cumsum(a):
    a = iter(a)
    b = [next(a)]
    for i in a:
        b.append(b[-1] + i)
    return np.array(b)




def hist_equ_11812418(input_image):
    # Insert code here
    img = Image.open(input_image)
    img_arr = np.asarray(img)
    img_flat = img_arr.flatten() #flatten image to 1D array

    #hist
    # plt.hist(img_flat, bins=50)
    # plt.show()
    input_img_hist = hist_arr(img_flat, 256)
    #print(hist)

    #sum

    # cumulative sum
    # execute the fn
    cumulative_sum = cumsum(input_img_hist)

    # display the cs
    # plt.plot(cs)
    # plt.show()

    #normalize
    cs_norm = ((cumulative_sum - cumulative_sum.min()) * 255)/(cumulative_sum.max() - cumulative_sum.min())
    cs_norm = cs_norm.astype('uint8')


    # plt.plot(cs_norm)
    # plt.show()


    img_new = cs_norm[img_flat]
    #print(img_new)
    img_new_arr = np.reshape(img_new, img_arr.shape)
    output_img_hist = hist_arr(img_new_arr, 256)

    #image file
    ouput_image = Image.fromarray(img_new_arr.astype(np.uint8))
    #hist file



    # return (ouput_image,input_img_hist,output_img_hist)
    return (ouput_image,img_flat,img_new)










 #return (output_image, output_hist, input_hist)




(oimg,input_hist,output_hist) = hist_equ_11812418("Q3_1_2.tif")

oimg.save("output/Q3_1_1_M.tif")

plt.hist(input_hist, bins=256)
plt.savefig('output/input_hist.png')

plt.clf()
plt.hist(output_hist, bins=256)
plt.savefig('output/output_hist.png')

lab3/hist_match.py

0 → 100755
+115 −0
Original line number Diff line number Diff line
import time
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

# define hist
hist = np.concatenate((np.linspace(0,10, 8 - 0),
                       np.linspace(10, 0.75, 16 - 8),
                       np.linspace(0.75, 0, 184 - 16),
                       np.linspace(0, 0.5, 200 - 184),
                       np.linspace(0.5, 0, 256 - 200)), axis=0)

spec_hist = np.zeros(256)




def hist_accumulation(hist, bins):
    histogram_in_data_normalized = hist / np.sum(hist)
    # historygram_accumulation
    histogram_in_data_accumulated = np.round(np.add.accumulate(histogram_in_data_normalized) * bins)

    return histogram_in_data_accumulated

def hist_normalization(hist, bins):
    histogram_in_data_normalized = hist / np.sum(hist)
    # historygram_accumulation

    return histogram_in_data_normalized


def hist_equ(img_flat, bins):
    bins_arr = np.arange(bins + 1)
    # generate histogram
    histogram_in_data, histogram_in_index = np.histogram(img_flat, bins=bins_arr)
    # history equ
    # histogram Normalized
    histogram_in_data_normalized = histogram_in_data / np.sum(histogram_in_data)
    # historygram_accumulation
    histogram_in_data_accumulated = np.round(np.add.accumulate(histogram_in_data_normalized) * bins)
    img_after_hist_equ = histogram_in_data_accumulated[img_flat]
    return histogram_in_data_accumulated, histogram_in_data, img_after_hist_equ


def hist_match(hist_in, hist_desired):
    hist_len = len(hist_in)
    hist_out = np.zeros(hist_len)

    def hist_match_index(i):
        index = min(range(hist_len), key=lambda j: abs(hist_desired[i] - hist_in[j]))
        hist_out[i] = index

    # def hist_match_index_par(i):
    #     return min(range(hist_len), key=lambda j: abs(hist_in[j] - hist_desired[i]))
    #
    # c = Parallel( n_jobs = 4 )( delayed( hist_match_index_par )( item ) for item in range(hist_len))
    # return c
    # init pool consume more time

    for i in range(hist_len):
        hist_match_index(i)
    return hist_out


def hist_match_11812418(input_image, spec_hist):
    # Insert code here
    img = Image.open(input_image)
    img_arr = np.asarray(img)
    img_flat = img_arr.flatten()  # flatten image to 1D array
    bins = 256

    # input img hist equ
    input_img_hist_after_hist_equ, input_hist, input_img_after_hist_equ = hist_equ(img_flat, bins)
    # desired_hist_normalized = hist_normalization(spec_hist, bins)
    desired_hist_accumulated = hist_accumulation(spec_hist, bins)
    # in: input_img_hist_after_hist_equ
    # desired: desired_hist_accumulated

    hist_lut = np.array(hist_match(input_img_hist_after_hist_equ, desired_hist_accumulated))

    plt.plot(input_img_hist_after_hist_equ)
    plt.show()
    plt.plot(desired_hist_accumulated)
    plt.show()

    img_after_hist_match = hist_lut[img_flat.astype(int) - 1]

    img_new_arr = np.reshape(input_img_after_hist_equ, img_arr.shape)
    output_hist, histogram_out_index = np.histogram(img_after_hist_match, bins=np.arange(bins + 1))

    return (img_new_arr, output_hist, input_hist)


def plot_hist(hist, filename, title):
    plt.figure(figsize=(8, 6), dpi=300)
    plt.plot(hist)
    plt.title(title)
    plt.savefig(filename)
    plt.show()


if __name__ == '__main__':
    # Q3_2
    start_time = time.time()
    (out_img2, hist_out, hist_in) = hist_match_11812418("Q3_2.tif", hist)

    op_image = Image.fromarray(out_img2.astype(np.uint8))
    print("--- %s seconds ---" % (time.time() - start_time))
    op_image.save("output/img/hist_matching/Q3_2_M.tif")
    op_image.save("output/img/hist_matching/Q3_2_M.png")

    plot_hist(hist_in, "output/img/hist_matching/Q3_2_hist.png", "Histogram before histogram matching")
    plot_hist(hist_out, "output/img/hist_matching/Q3_2_M_hist.png", "Histogram after histogram matching")
    plot_hist(hist, "output/img/hist_matching/hist.png", "Histogram used to match")

lab3/local_hist_equ.py

0 → 100755
+77 −0
Original line number Diff line number Diff line
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import time
def hist_equ(img_flat,bins):
    bins_arr = np.arange(bins + 1)
    # generate histogram
    histogram_in_data, histogram_in_index = np.histogram(img_flat, bins=bins_arr)
    # print(histogram_in_data)

    # history equ
    # histogram Normalized
    histogram_in_data_normalized = histogram_in_data / np.sum(histogram_in_data)
    # historygram_accumulation
    histogram_in_data_accumulated = np.round(np.add.accumulate(histogram_in_data_normalized) * bins)
    # plt.plot(histogram_in_data_accumulated)
    # plt.show()


    img_after_hist_equ = histogram_in_data_accumulated[img_flat]


    return histogram_in_data_accumulated, img_after_hist_equ


def local_hist_equ_11812418(input_image):
    # Insert code here
    img = Image.open(input_image)
    img_arr = np.asarray(img)
    img_flat = img_arr.flatten() #flatten image to 1D array
    bins = 256


    input_img_hist_after_hist_equ, input_img_after_hist_equ = hist_equ(img_flat, bins)
    plt.hist(input_img_after_hist_equ,256)
    plt.show()
    print(input_img_after_hist_equ)
    # #print for test
    # img_new_arr = np.reshape(input_img_after_hist_equ, img_arr.shape)
    # ouput_image = Image.fromarray(img_new_arr.astype(np.uint8))
    # ouput_image.save("output/0311-1.tif")



    return ()

def local_hist_equ(in_img, m_size):
    """
    Implement the local histogram equalization to the input images Q3_3.tif
    """
    img = Image.open(in_img)
    in_img = np.asarray(img)
    row, col = in_img.shape
    out_img = np.zeros(in_img.shape, int)

    bin_num = 256
    bins = range(bin_num + 1)
    for i in list(range(0, row - m_size, m_size)) + [row - m_size - 1]:
        # i = min(i, row - m_size)
        for j in list(range(0, col - m_size, m_size)) + [col - m_size - 1]:
            # j = min(j, col - m_size)
            local_img = in_img[i:i + m_size, j:j + m_size]
            local_hist, _ = np.histogram(local_img.flat, bins=bins, density=True)
            s = np.array([(bin_num - 1) * np.sum(local_hist[:k + 1]) for k in range(bin_num)])
            out_img[i:i + m_size, j:j + m_size] = np.array([s[r] for r in local_img], int).reshape((m_size, m_size))



    return out_img


# local_hist_equ_11812418("Q3_3.tif")
start_time = time.time()
out_img2 = local_hist_equ("Q3_3.tif",2)
ouput_image = Image.fromarray(out_img2.astype(np.uint8))
print("--- %s seconds ---" % (time.time() - start_time))
ouput_image.save("output/0311-2.tif")
 No newline at end of file
Loading