Python Forum
Help with datatypes and conversion between them
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with datatypes and conversion between them
#1
I am using opencv to do a simple task, namely draw a rectangle with a certain colour. I have used opencv in the past with python to do simple things, but it seems I don't always understand the nature of basic datatypes.

If I use something like this it works without issues;

colour = (123,123,123)
cv2.rectangle(img_palette, (0, 0), (512, 512), colour ,cv2.FILLED);
Now here's the fun bit. I pinched a bit of code from the internet that I don't fully understand, but in a nutshell it returns a dominant colour, but this colour is I believe in the format of a vector array generated from numpy (please correct me if i'm wrong).
colour = palette[np.argmax(counts)]
When I print the contents of the resultant colour it is in the format of;
Output:
[123.12 123.12 123.12]
I can use astype(int) to convert the contents to an int, which becomes;
intcolour = colour.astype(int)
Output:
[123 123 123]
And if I did
drawcolour  = (intcolour[0],intcolour[1],intcolour[2])
then it appears to output;
Output:
(123, 123, 123)
but I can't pass this value to the rectangle function; I get..
Error:
cv2.rectangle(img_palette, (0, 0), (512, 512), drawcolour ,cv2.FILLED); TypeError: an integer is required (got type tuple)
but the opencv docs clearly state;
Quote:color: It is the color of border line of rectangle to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.
So I believe I am passing the correct datatype, even if I am going a weird way to get there.


I usually can figure these things out but here I am completely in the dark, numpy is a little alien to me, and i'm having difficulty working out what to search for, any help appreciated as i'm sure it's an easy fix but it has had me stumped for a while now.
Reply
#2
Not certain, but there's a discussion about a similar issue on the opencv github. It's the same error message, but it's not related to the color tuple. I'm not familiar with opencv, so I'm not sure I'm following the discussion well.
Reply
#3
(Sep-12-2020, 08:01 PM)bowlofred Wrote: Not certain, but there's a discussion about a similar issue on the opencv github. It's the same error message, but it's not related to the color tuple. I'm not familiar with opencv, so I'm not sure I'm following the discussion well.

Thanks for the info. Had a long look at that post and through a bit of trial and error it seems the fault was in the method of data conversion. Basically in my colour variable numpy returned the individual elements as type numpy.int32, but opencv required the colour parameters as simply int, so in a nutshell I do;

workingcolour  = (int(numpycolour[0]),int(numpycolour[1]),int(numpycolour[2]))


And this solves the issue. Thanks.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020