Victor Simon
Victor Simon

Reputation: 85

Want to append colored images to a list and convert that list to grayscale using OpenCV

So basically I'm trying to convert a set of RGB images to grayscale using cv2.cvtColor and python is throwing the following error:

Traceback (most recent call last): File "MCG.py", line 53, in gray = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)
TypeError: src is not a numpy array, neither a scalar.

This here is the code:

import numpy as np  
import cv2  
import dlib
import sys
import skimage 
from PIL import Image
import os
import glob


folderpath = sys.argv[1]
cascPath = sys.argv[2]

imageformat = ".tif"
path = folderpath
imfilelist = [os.path.join(path,f) for f in os.listdir(path) if f.endswith(imageformat)]
data = []
for IMG in imfilelist:
   print IMG
   image = cv2.imread(IMG)
   data.append(image)
   cv2.imshow('Image', image)
   cv2.waitKey(0)

faceCascade = cv2.CascadeClassifier(cascPath)  

predictor = dlib.shape_predictor(PREDICTOR_PATH)  

gray = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)  

faces = faceCascade.detectMultiScale(  
    gray,  
    scaleFactor=1.05,  
    minNeighbors=5,
    minSize=(100,100)
)

As you can see, I'm trying to append all these images to a list, which will then be converted using the cv2.cvtColor function. However, that error is thrown. What am I doing wrong? Thank you.

P.S if anyone is wondering why I imported modules that don't seem to be used in this code, this code is just a segment of the whole thing and all of those modules have are being utilized in one way or the other.

Upvotes: 2

Views: 6520

Answers (2)

lamo_738
lamo_738

Reputation: 440

If you read the cv2.cvtColor documentation, you can see that the first parameter is the Src 8-bit single channel image. However, in your case you are giving an entire list of images. So change the code as

gray = []
for j in range(0,len(data)):
    gray.append(cv2.cvtColor(np.array(data[j]), cv2.COLOR_BGR2GRAY))

I guess this should work.

Upvotes: 1

Mick
Mick

Reputation: 910

You are collecting the images into a list with

data = []
for IMG in imfilelist:
    ...
    data.append(image)
    ....

and then trying to convert the list with

gray = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)  

This is why you are getting the error - the error is telling you that data is not an image (numpy array) but is a list. You need to convert one image at a time with cv2.cvtColor().

You could try

gray = []
for img in data:
    gray.append(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))

This would give you a list of greyscaled images, which is what I think you want to do.

Upvotes: 2

Related Questions