Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Histogram Equalization Python For Colored Image

Tags:

python

opencv

I'm new at Opencv thing and

I'm trying to do Histogram Equalization manual way and somehow my output is like this

First i convert the format to YCR_CB format first and then split it into each y,cr and cb . And then i did the histogram equalization thing on layer y.

here's my code :

    from __future__ import division
    import cv2
    import numpy as np

    img1 = cv2.imread("sup.jpg")

    img2 = cv2.cvtColor(img1,cv2.COLOR_BGR2YCR_CB)

    y,cr,cb = cv2.split(img2)

    #y = cv2.equalizeHist(y)

    x =y

    height,width = y.shape

    hist = [0]*256
    pmf = [0]*256
    cdf = [0]*256
    levelBaru = [0]*256

    cv2.imshow("y before",x)
    cv2.waitKey(0)

    for i in range(0,height):  
        for j in range(0,width):
            hist[y.item(i,j)] += 1 
            #hist[y[i,j]] += 1

    for i in range(0,256):  
            #cari pmf
        pmf[i] = round(hist[i]/(height*width),4)

    print "pmf  done"

    cdf[0] = pmf[0]

    for i in range(1,256):              #cari cdf
        cdf[i] = cdf[i-1]+pmf[i]

    for i in range(1,256):              #cari levelBaru
        levelBaru[i] = int(cdf[i]*255)

    for i in range(0,height):           #baru
        for j in range(0,width):
            for k in range (0,256):
                if(y.item(i,j)==k):
                    #print i," ",levelBaru[i]
                    y.itemset((i,j),levelBaru[k])

    img2 = cv2.merge((y,cr,cb))
    img2 = cv2.cvtColor(img2,cv2.COLOR_YCR_CB2BGR) #supaya ga error pas di stack


    #cv2.namedWindow('result', cv2.WINDOW_NORMAL)
    cv2.imshow('result',img2)

    cv2.waitKey(0)
    cv2.destroyAllWindows

Kinda stuck finding the bug , if someone can help me that would be awesome

like image 859
Johnny21 Avatar asked Dec 11 '25 02:12

Johnny21


1 Answers

As per the question title you want to equalize the histogram of a colored image, by splitting it in YCrCb domain. There is no point in writing your own algorithm for equalizing histogram, as it seems in the code snippet attached, OpenCV already has a method as cv2.eqHist() to serve your purpose.

import cv2

img = cv2.imread("path/to/Lenna.png")

img_y_cr_cb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
y, cr, cb = cv2.split(img_y_cr_cb)

# Applying equalize Hist operation on Y channel.
y_eq = cv2.equalizeHist(y)

img_y_cr_cb_eq = cv2.merge((y_eq, cr, cb))
img_rgb_eq = cv2.cvtColor(img_y_cr_cb_eq, cv2.COLOR_YCR_CB2BGR)

Input:

enter image description here

Output:

enter image description here

like image 140
ZdaR Avatar answered Dec 13 '25 16:12

ZdaR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!