Reputation: 765
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'):
cv2.destroyAllWindows()
# if I press yes, save and destroy
if cv2.waitKey(0) & 0xFF == ord('y'):
filename = str(item) + '.jpg'
cv2.imwrite(filename, newCs)
cv2.destroyAllWindows()
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?
Thanks
Upvotes: 0
Views: 420
Reputation: 22954
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))
Upvotes: 1