Convert RGB to black OR white

后端 未结 8 1165
我在风中等你
我在风中等你 2020-11-30 23:20

How would I take an RGB image in Python and convert it to black OR white? Not grayscale, I want each pixel to be either fully black (0, 0, 0) or fully white (255, 255, 255).

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 23:35

    Using opencv You can easily convert rgb to binary image

    import cv2
    %matplotlib inline 
    import matplotlib.pyplot as plt
    from skimage import io
    from PIL import Image
    import numpy as np
    
    img = io.imread('http://www.bogotobogo.com/Matlab/images/MATLAB_DEMO_IMAGES/football.jpg')
    img = cv2.cvtColor(img, cv2.IMREAD_COLOR)
    imR=img[:,:,0] #only taking gray channel
    print(img.shape)
    plt.imshow(imR, cmap=plt.get_cmap('gray'))
    
    #Gray Image
    plt.imshow(imR)
    plt.title('my picture')
    plt.show()
    
    #Histogram Analyze
    
    imgg=imR
    hist = cv2.calcHist([imgg],[0],None,[256],[0,256])
    plt.hist(imgg.ravel(),256,[0,256])
    
    # show the plotting graph of an image
    
    plt.show()
    
    #Black And White
    height,width=imgg.shape
    for i in range(0,height):
      for j in range(0,width):
         if(imgg[i][j]>60):
            imgg[i][j]=255
         else:
            imgg[i][j]=0
    
    plt.imshow(imgg)
    

提交回复
热议问题