How can I convert an RGB image into grayscale in Python?

前端 未结 12 1124
Happy的楠姐
Happy的楠姐 2020-11-22 04:43

I\'m trying to use matplotlib to read in an RGB image and convert it to grayscale.

In matlab I use this:

img = rgb2gray(imread(\'image.p         


        
12条回答
  •  遥遥无期
    2020-11-22 05:13

    Three of the suggested methods were tested for speed with 1000 RGBA PNG images (224 x 256 pixels) running with Python 3.5 on Ubuntu 16.04 LTS (Xeon E5 2670 with SSD).

    Average run times

    pil : 1.037 seconds

    scipy: 1.040 seconds

    sk : 2.120 seconds

    PIL and SciPy gave identical numpy arrays (ranging from 0 to 255). SkImage gives arrays from 0 to 1. In addition the colors are converted slightly different, see the example from the CUB-200 dataset.

    SkImage:

    PIL :

    SciPy :

    Original:

    Diff :

    Code

    1. Performance

      run_times = dict(sk=list(), pil=list(), scipy=list())
      for t in range(100):
          start_time = time.time()
          for i in range(1000):
              z = random.choice(filenames_png)
              img = skimage.color.rgb2gray(skimage.io.imread(z))
          run_times['sk'].append(time.time() - start_time)

      start_time = time.time()
      for i in range(1000):
          z = random.choice(filenames_png)
          img = np.array(Image.open(z).convert('L'))
      run_times['pil'].append(time.time() - start_time)
      
      start_time = time.time()
      for i in range(1000):
          z = random.choice(filenames_png)
          img = scipy.ndimage.imread(z, mode='L')
      run_times['scipy'].append(time.time() - start_time)
      

      for k, v in run_times.items(): print('{:5}: {:0.3f} seconds'.format(k, sum(v) / len(v)))

    2. Output
      z = 'Cardinal_0007_3025810472.jpg'
      img1 = skimage.color.rgb2gray(skimage.io.imread(z)) * 255
      IPython.display.display(PIL.Image.fromarray(img1).convert('RGB'))
      img2 = np.array(Image.open(z).convert('L'))
      IPython.display.display(PIL.Image.fromarray(img2))
      img3 = scipy.ndimage.imread(z, mode='L')
      IPython.display.display(PIL.Image.fromarray(img3))
      
    3. Comparison
      img_diff = np.ndarray(shape=img1.shape, dtype='float32')
      img_diff.fill(128)
      img_diff += (img1 - img3)
      img_diff -= img_diff.min()
      img_diff *= (255/img_diff.max())
      IPython.display.display(PIL.Image.fromarray(img_diff).convert('RGB'))
      
    4. Imports
      import skimage.color
      import skimage.io
      import random
      import time
      from PIL import Image
      import numpy as np
      import scipy.ndimage
      import IPython.display
      
    5. Versions
      skimage.version
      0.13.0
      scipy.version
      0.19.1
      np.version
      1.13.1
      

提交回复
热议问题