Home > Net >  How can I convert real image to black and white image perfectly?
How can I convert real image to black and white image perfectly?

Time:06-29

I have used the Grey and Threshold tool of the Open CV library. However, it is not giving satisfying results. do any one knows any other method to convert the image into the b&w images. Check below, I have attached some of the bw images, that are so accurate.

enter image description here enter image description here

CodePudding user response:

I'm not sure that you tried cv2.cvtColor(<ImagePath>, cv2.COLOR_BGR2GRAY). This code changing it to GrayScale image. I tried it myself using your uploaded image and it's works. Here is the full code.

import cv2
grayImage = cv2.imread('jeY9D.jpg')
grayImage = cv2.cvtColor(grayImage, cv2.COLOR_BGR2GRAY)
cv2.imshow('Testing', grayImage)
cv2.waitKey(0)
cv2.destoryAllWindows()

And here is the result.enter image description here

CodePudding user response:

If u want flexibility u can just make ur own function that map a pixel on ur img to black or white if it is below or above a given threshold


def bin(img, threshold=128):
    bin_img= np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8)
    
    for i in range(img.shape[1]):
        for j in range(img.shape[0]):
            bin_img[j, i]= 0 if(img[j, i]<threshold) else 255

    return np.uint8(bin_img)

Here is an example if using 3 different threshold

img_t_64= bin(img, 64)
img_t_128= bin(img)
img_t_192= bin(img, 192)


fig = plt.figure(figsize=(14, 6))

ax = fig.add_subplot(131)
ax2 = fig.add_subplot(132)
ax3 = fig.add_subplot(133)

ax.set_title(f'threshold={64}')
ax2.set_title(f'threshold={128}')
ax3.set_title(f'threshold={192}')

ax.imshow(img_t_64, 'gray')
ax2.imshow(img_t_128, 'gray')
ax3.imshow(img_t_192, 'gray')

plt.show()

enter image description here

  • Related