我是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
有点找不到这个错误,如果有人可以帮助我那将是很棒的
答案 0 :(得分:2)
根据问题标题,您希望通过在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)
输入:
输出