我是Opencv的新人

我正在尝试以手动方式进行直方图均衡化,但我的输出却像
this

首先,我首先将格式转换为YCR_CB格式,然后将其拆分为每个y,cr和cb。然后我在y层上进行了直方图均衡化处理。

这是我的代码:

    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会发现该错误,那真是太棒了

最佳答案

根据问题标题,您想通过在YCrCb域中进行拆分来均衡彩色图像的直方图。编写自己的均衡直方图的算法没有任何意义,就像所附的代码片段中所示,OpenCV已经有一种作为cv2.eqHist()的方法可以满足您的目的。

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)

输入:

python - 彩色图像的直方图均衡化Python-LMLPHP

输出:

python - 彩色图像的直方图均衡化Python-LMLPHP

关于python - 彩色图像的直方图均衡化Python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42651595/

10-12 01:43