Reputation: 619
I am trying to perform histogram equalization on an image an have 2 issues. First, I need to plot the histogram for the grayscale version of it. When I try to convert the RGB image to grayscale the output is a blue and yellow image. My code goes as follows:
img = cv2.imread(r'D:/UNI/Y3/DIA/2K18/lab.jpg')
RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(RGB_img, cv2.COLOR_RGB2GRAY)
plt.imshow(gray)
plt.title('My picture (before hist. eq.)')
plt.show()
This is Jupyter Notebook's output:
But I just realized that if I save if it saves it correctly:
Since I need to hand in the jupyter doc how could I overcome this issue? Thx!
Second, I perform Histogram equalization but when trying to stack the images horizontally I get the following error form this code:
equ = cv2.equalizeHist(gray)
res = np.hstack((img,equ))
error -> all the input arrays must have same number of dimensions
As far as I can see I didn't touch the images' dimensions at all...
EDIT:
The left image should be RGB
Upvotes: 1
Views: 10838
Reputation: 22954
As @Fredrik suggested, you can use plt.imshow(gray, cmap='gray', vmin = 0, vmax = 255)
to get you a grayscale output or you can also convert the Grayscale image to a 3 channel RGB image using gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB)
.
Basically the problem is that gray = cv2.cvtColor(RGB_img, cv2.COLOR_RGB2GRAY)
returns a single channel matrix, where as matplotlib is expecting a 3 channel RGB matrix to be shown, So you can either tell plt.imshow()
that your input matrix is a single channel matrix using plt.imshow(gray, cmap='gray', vmin = 0, vmax = 255)
or you can simply convert the single channel matrix to 3 channel matrix and then simply use plt.imshow(gray)
and everything would work fine.
For the second part of your question where res = np.hstack((img,equ))
is raising error, it is always helpful to debug the shape of matrices, you want to apply operation upon, You can do that by print img.shape
, print equ.shape
. As far as I can see your img
is a 3-channel matrix (BGR), whereas your equ
is a single channel matrix (gray), hence error, you would need to convert this equ
matrix to a 3-channel matrix again using cv2.cvtColor(equ, cv2.COLOR_GRAY2RGB)
.
Upvotes: 9