SoFunction
Updated on 2024-11-10

Summary of the four methods (OpenCV,, TensorFlow methods) for python3 to read and grayscale images

When working with images it is often a matter of reading the image and then converting it to grayscale. As a newbie, I've documented four ways to do this in this blog.

First import the package:

import numpy as np
import cv2
import tensorflow as tf
from PIL import Image

Method 1: Convert the image to grayscale while reading it using OpenCV:

 img = (imgfile, cv2.IMREAD_GRAYSCALE)
  print("(imgfile, cv2.IMREAD_GRAYSCALE)The results are as follows:")
  print('adults and children:{}'.format())
  print("Type: %s"%type(img))
  print(img)

The results of the run are shown below:

Method 2: Using OpenCV, read the image first and then convert it to grayscale:

 img = (imgfile)
  #print()
  #print(img)
  gray_img = (img, cv2.COLOR_BGR2GRAY) #Y = 0.299R + 0.587G + 0.114B
  print("(img, cv2.COLOR_BGR2GRAY)The results are as follows:")
  print('adults and children:{}'.format(gray_img.shape))
  print("Type: %s" % type(gray_img))
  print(gray_img)

The results of the run are as follows:


Method 3: Use the Image module in the PIL library

 img = ((imgfile).convert('L'), 'f') # Read image, grayscale, convert to array, L = 0.299R + 0.587G + 0.114B. 'f' is of type float
  print("The result of the Image method is as follows:")
  print('adults and children:{}'.format())
  print("Type: %s" % type(img))
  print(img)

The results of the run are as follows:


For more knowledge about using the convert() function of the Image module in the PIL library, please refer to the blog: https:///kf/201603/

Method 4: TensorFlow method:

 with () as sess:
    img = tf.read_file(imgfile) #Read the pictures.
    img_data = .decode_jpeg(img, channels=3) #Decode
    #img_data = (.decode_jpeg(img, channels=3))
    img_data = (.rgb_to_grayscale(img_data)) # Graying out
    print('adults and children:{}'.format(img_data.shape))
    print("Type: %s" % type(img_data))
    print(img_data)

The results of the run are as follows:



As you can see: the results of TensorFlow's method are slightly different from the processing results of the three methods above. So it is better to keep the consistency of the methods when processing images, and it is better not to read the image with this method and then process the image with another method, in order to avoid unnecessary bugs affecting the results of image processing.

This is the whole content of this article.