简体   繁体   中英

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?

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

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 (ie for z in range(img1.shape[2]) ) instead.)

Thread closed!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM