I am trying to make a simple program that shows me what the first frame of a video looks like when it's converted into the different colourspaces available in openCV.

I am trying to use an iterator like this:

for item in flags:
    arg = 'cv2.' + str(item)
    newCs = cv2.cvtColor(frame, arg)

    cv2.imshow('newCs', newCs)
    # if I press no, destroy
    if cv2.waitKey(0) & 0xFF == ord('n'):
    # if I press yes, save and destroy
    if cv2.waitKey(0) & 0xFF == ord('y'):
       filename = str(item) + '.jpg'
       cv2.imwrite(filename, newCs)

where 'flags' is an array containing all the flags like 'COLOR_BGR2HSV' and arg successfully returns a string that looks like the flag you would enter manually into the function eg. 'cv2.COLOR_BGR2HSV'

This program returns an error, saying that it was expecting an int in place of 'arg'

Is this because what I'm trying to do is impossible, or is there a way of doing this?


what do you mean by "what it looks like"? Color spaces are more like how to encode color. Do you mean "how different color spaces look like when interpreted as BGR during rendering"?? – Micka 1 hour ago
Tbh I'm brand new to openCV and all this image processing stuff, but I found if I converted an image to a different colourspace (ie. HSV), when I used the imshow() method on it, it looks different. Is that merely due to the computer display rendering it expecting a BGR image? – strava 1 hour ago
yes that's right, imshow assumes BGR and renders as if it was BGR. OpenCV functions don't even know in which color space an image is represented. – Micka 1 hour ago
Ok, thanks for pointing that out, that's simplified some things – strava 44 mins ago
Ok that makes sense, thanks for pointing that out, it simplifies a few things – strava 39 mins ago

1 Answer 1

The error hints, that second param of cv2.cvtColor(), must be int code which tells the method which conversion formula needs to be invoked. And you are trying to pass a str value where, int is required.

Why would you store COLOR_BGR2HSV as str in a list and later concatenate it with "cv2." to make the situation more complex. You may simply create a list as color_configs = [cv2.COLOR_BGR2GRAY, cv2.COLOR_BGR2HSV, ...] and later iterate it to get the job done.

However, if you have no way to changing that list, then there is a hacky way to do the same, I won't recommend you to follow that in first place. But you may use eval, with taking proper precautions and sanitizing the string input, before calling eval as:

for item in flags:
    mode = 'cv2.' + str(item)
    newCs = cv2.cvtColor(frame, eval(mode))
That's solved it, thanks, just an oversight/overcomplication on my part – strava 40 mins ago