title: How fast in Python change 3 channel rgb color image to 1 channel gray?
body: <p>I have almost 40000 images in a 4D array containing raw pixel data - (number of examples, width, height, channels). Every image has width of 32 pixels, height of 32 pixels, and 3 channels for RGB colors. I want to change them to grayscale images (from 3 channels with rgb get 1 with intensity). How I can do it quite fast?
  My code:</p>
  
  <pre><code>import pickle
  import cv2
  training_file = "/train.p"
  
  with open(training_file, mode='rb') as f:
  train = pickle.load(f)
  X_train = train['features']
  
  def rgb2gray(rgb):
      r, g, b = rgb[0], rgb[1], rgb[2]
      gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
  return gray
  
  X_train_gray = X_train.copy()
  
  for i in range (X_train_gray.shape[0]):
      for j in range (X_train_gray.shape[1]):
          for k in range (X_train_gray.shape[2]):
              rgb = X_train_gray[i,j,k]
              gray = rgb2gray(rgb)
              X_train_gray[i,j,k] = gray
  
  print("X_train image data shape =", X_train.shape)
  print("X_train_grey image data shape =", X_train_gray.shape)
  </code></pre>
  
  <p>Result:<br>
  X_train_grey image data shape = (40000, 32, 32, 3)<br>
  X_train_grey image data shape = (40000, 32, 32, 1)<br>
  It's good, but it takes a lot of time. </p>
  
  <p>I also tried to use cv2:</p>
  
  <pre><code>X_train_gray = X_train[0].copy()
  print("X_train_grey image data shape =", X_train_gray.shape)
  X_train_gray = cv2.cvtColor(X_train_gray, cv2.COLOR_BGR2GRAY)
  print("X_train_grey image data shape =", X_train_gray.shape)
  </code></pre>
  
  <p>Result:<br>
  X_train_grey image data shape = (32, 32, 3)<br>
  X_train_grey image data shape = (32, 32)<br>
  But I lose intensity and don't know how to get it.<br>
  So how in fast way I can change this images from 3 channel rgb to 1 channel gray?</p>