convert image to grayscale python code example

Example 1: python image to grayscale

from PIL import Image
img = Image.open("image.jpg")
img.convert("L").save("result.jpg")

Example 2: convert an image to grayscale python using numpy array

1
2
3
4
5
6
7
import numpy as np
from PIL import Image

im = np.array(Image.open('kolala.jpeg').convert('L')) #you can pass multiple arguments in single line
print(type(im))

gr_im= Image.fromarray(im).save('gr_kolala.png')

Example 3: python pil to greyscale

#PIL image
img2 = img.convert('L')

Example 4: how to convert into grayscale opencv

import cv2

# Reading color image as grayscale
gray = cv2.imread("color-img.png",0)

# Showing grayscale image
cv2.imshow("Grayscale Image", gray)

# waiting for key event
cv2.waitKey(0)

# destroying all windows
cv2.destroyAllWindows()

Example 5: cvtcolor rgb to gray

cv::Mat img
cv::cvtColor(img, img, CV_BGR2GRAY);