Reputation: 1029
While I know how to convert a single color image (32,32,3) to grayscale using CV2
:
img = cv2.cvtColor( img, cv2.COLOR_RGB2GRAY )
I need to convert a batch of 60,000 images in a 4D numpy array (60000,32,32,3), how can I achieve that?
Upvotes: 1
Views: 1300
Reputation: 2945
One more option using numpy
:
grayscale_imgs = np.dot(img_stack, [0.299 , 0.587, 0.114])
grayscale_imgs.shape # => (60000, 32, 32)
More about the weighted sum can be found here
Upvotes: 1
Reputation: 8324
Let's say your 4D array of images is called img_stack
with shape (60000,32,32,3).
You could do:
gray_stack = np.empty_like(img_stack[...,0])
for i in range(img_stack.shape[0]):
gray_stack[i] = cv2.cvtColor(img_stack[i], cv2.COLOR_RGB2GRAY)
Resulting shape is (60000,32,32).
Or you could do:
gray_stack = np.empty_like(img_stack[...,:1])
for i in range(img_stack.shape[0]):
gray_stack[i,:,:,0] = cv2.cvtColor(img_stack[i], cv2.COLOR_RGB2GRAY)
Resulting shape is (60000,32,32,1).
Bonus Tensorflow solution:
gray_stack = tf.image.rgb_to_grayscale(img_stack, name=None)
Resulting shape will be (60000,32,32,1).
The above OpenCV solutions might actually perform faster.
Upvotes: 2