Dromeda
Dromeda

Reputation: 113

Translating the comparision operator in OpenCV to Python

I'm trying to translate some OpenCV codes written in C++ to Python. Here's the C++ code I encountered:

img2 = img1 >= 128;

where both img2 and img1 are of type cv::Mat.

It seems that in the OpenCV library for Python there is no such function that does the job equivalent to the operator overloading here. How could I possibly translate this?

Upvotes: 1

Views: 81

Answers (2)

Guimoute
Guimoute

Reputation: 4649

array >= 128 should produce a boolean array that you can then convert to int and multiply by 255 to get what you want. It should be order of magnitudes faster than for loops.

Otherwise there is also

mask = (img1 >= 128) # Parenthesis are not needed, I just like them to surround the new object. 
img2[mask] = 255
img2[~mask] = 0

Upvotes: 1

Dromeda
Dromeda

Reputation: 113

Alas, it seems that only entrywise calculation works properly here. Directly using the operator >= produces an array that has some typing issues in Python OpenCV, while in C++ there is no such problem.

img2 = numpy.zeros(img1.shape, dtype=numpy.uint8)
  for x in range(img1.shape[0]):
    for y in range(img1.shape[1]):
      if img1[x][y] >= 128:
        img2[x][y] = 255
      else:
        img2[x][y] = 0

(By the way, img1 has been channel-extracted so it is 2-dimensional. If mg1 composes of multiple channels, go through a third iteration on this extra dimension (i.e. for z in range(img1.shape[2])) instead.)

Thread closed!

Upvotes: 0

Related Questions