mohammed hossam
mohammed hossam

Reputation: 45

histogram equalization for colored image give error using python opencv

Error : Assertion failed (0 < cn && cn <= CV_CN_MAX) in merge

In the merge function

cv2.merge(channels,img2)

if the arguments are replaced as shown:

cv2.merge(img2,channels)

it will not give an error, but the histograms will be the same before and after equalization. What can I do in this piece of code.

Code:

import cv2,cv
import cv2.cv as cv
import numpy as np
from matplotlib import pyplot as plt

capture = cv.CaptureFromCAM(0)
img = cv.QueryFrame(capture)
img_size = cv.GetSize(img)

width,height = img_size
size = width,height,3
channels = np.zeros(size , np.uint8) 


while (1):
img = cv.QueryFrame(capture)
img = np.asarray(img[:,:])

cv2.imshow("original",img)
hist = cv2.calcHist([img],[2],None,[256],[0,256])

#convert img to YCR_CB
img2 = cv2.cvtColor(img,cv2.COLOR_BGR2YCR_CB)

#split image to Y, CR, CB
cv2.split(img2,channels)

#histogram equalization to Y-MATRIX
cv2.equalizeHist(channels[0],channels[0])

#merge this matrix to reconstruct our colored image
cv2.merge(channels,img2)

#convert this output image to rgb
rgb = cv2.cvtColor(img2,cv2.COLOR_YCR_CB2BGR)
hist2 = cv2.calcHist([rgb],[2],None,[256],[0,256])
plt.plot(hist)
plt.plot(hist2)
plt.show()

Upvotes: 1

Views: 3310

Answers (2)

Froyo
Froyo

Reputation: 18477

Instead of using split and merge, take advantage of numpy slicing.

img2[:, :, 0] = cv2.equalizeHist(img2[:, :, 0]) 
# or run a small loop over each channel

Upvotes: 6

berak
berak

Reputation: 39796

you got the split() wrong here. it returns the channels.

since you don't catch the return values, your channels are not initialized

>>> import cv2
>>> help(cv2.split)
Help on built-in function split in module cv2:

split(...)
    split(m[, mv]) -> mv

so it should look like:

channels = cv2.split(img2)

and please, avoid the old cv api, instead stick with cv2 consistently. (use cv2.VideoCapture, not cv.CaptureFromCAM)

Upvotes: 2

Related Questions