Dian Arief R
Dian Arief R

Reputation: 89

How to create histogram of binary image?

I have binary image (only 2 color, black and white), Binary Image

I want to create histogram of the image. I have tried with these code:

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('bin_003.png')
color = ('b','g','r')
for i,col in enumerate(color):
    histr = cv2.calcHist([img],[i],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])
plt.show()

But the code shows Histogram instead of showing only 0 and 1 at the x axis.

Upvotes: 1

Views: 5601

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339660

Since you have a black and white image here, it should only have a single channel. You wouldn't need RGB channels. You may create a single histogram by using plt.hist.

from matplotlib import pyplot as plt

img = plt.imread('https://i.sstatic.net/y19dr.png')

plt.hist(img.flatten(), bins=[-.5,.5,1.5], ec="k")
plt.xticks((0,1))
plt.show()

enter image description here

Upvotes: 4

Related Questions