1

I know that there have been many similar questions around, but none of those seem to work for my problem. That's why I decided to create another post.

To start off, the basic idea of the following code is that it will detect the pixel value of a specific coordinate in order to create a rectangle with the same color.

This is my code:

# open image
img = cv2.imread("image.png")

# set coordinates for rectangle
start_point = (35, 39) 
end_point = (50, 60)

# get pixel value of start point; outputs something like "[132 42 52]"
pixel = img[start_point].astype(int) 
R = pixel[0]
G = pixel[1]
B = pixel[2]

# outputs type: "<class 'numpy.ndarray'> <class 'numpy.int32'> <class 'numpy.int32'> <class 'numpy.int32'>"
print(type(pixel), type(R), type(G), type(B))

# draws rectangle
color = (R, G, B)
image = cv2.rectangle(img, start_point, end_point, color, -1)

Even though the values "R", "G" and "B" are converted into integers by using "astype(int)" I get the following error:

image = cv2.rectangle(img, start_point, end_point, color, -1)
TypeError: an integer is required (got type tuple)

By using numbers like 30, 53, 100 as the color values everything works out perfectly fine. There just seems to be a problem with the values I receive by setting the pixel value of a coordinate in this image. I don't really know where the problem could be, so I appreciate every help!

Thanks in advance.

2 Answers 2

2

I think the simplest solution is using color = (int(R), int(G), int(B)).

The issue is that even when using pixel = img[start_point].astype(int), the elements of pixel are of type <class 'numpy.int32'> and not of type int.

Sign up to request clarification or add additional context in comments.

Comments

2

You answered yourself - you passed type numpy.int32 and they expect int. For humans it's the same, but python has a hard time handling all types convertible to one another. You have to help them by passing:

image = cv2.rectangle(img, start_point, end_point, [int(x) for x in color], -1)

1 Comment

Oh wow, my bad. Based on lack of knowledge I didn't even know that there's a difference between Int32 and a "normal" integer. Thank you very much! @NadavS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.