Convert RGB to black OR white
Scaling to Black and White
Convert to grayscale and then scale to white or black (whichever is closest).
Original:
Result:
Pure Pillow implementation
Install pillow
if you haven't already:
$ pip install pillow
Pillow (or PIL) can help you work with images effectively.
from PIL import Imagecol = Image.open("cat-tied-icon.png")gray = col.convert('L')bw = gray.point(lambda x: 0 if x<128 else 255, '1')bw.save("result_bw.png")
Alternatively, you can use Pillow with numpy.
Pillow + Numpy Bitmasks Approach
You'll need to install numpy:
$ pip install numpy
Numpy needs a copy of the array to operate on, but the result is the same.
from PIL import Imageimport numpy as npcol = Image.open("cat-tied-icon.png")gray = col.convert('L')# Let numpy do the heavy lifting for converting pixels to pure black or whitebw = np.asarray(gray).copy()# Pixel range is 0...255, 256/2 = 128bw[bw < 128] = 0 # Blackbw[bw >= 128] = 255 # White# Now we put it back in Pillow/PIL landimfile = Image.fromarray(bw)imfile.save("result_bw.png")
Black and White using Pillow, with dithering
Using pillow you can convert it directly to black and white. It will look like it has shades of grey but your brain is tricking you! (Black and white near each other look like grey)
from PIL import Image image_file = Image.open("cat-tied-icon.png") # open colour imageimage_file = image_file.convert('1') # convert image to black and whiteimage_file.save('/tmp/result.png')
Original:
Converted:
Black and White using Pillow, without dithering
from PIL import Image image_file = Image.open("cat-tied-icon.png") # open color imageimage_file = image_file.convert('1', dither=Image.NONE) # convert image to black and whiteimage_file.save('/tmp/result.png')
I would suggest converting to grayscale, then simply applying a threshold (halfway, or mean or meadian, if you so choose) to it.
from PIL import Imagecol = Image.open('myimage.jpg')gry = col.convert('L')grarray = np.asarray(gry)bw = (grarray > grarray.mean())*255imshow(bw)
img_rgb = cv2.imread('image.jpg')img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)(threshi, img_bw) = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)