cv2.compare() in OpenCV Python. What does this code snippet mean?

Viewed 58
def volume_analysis(self, threshold_image):
    gamma = 0.05
    flag = False
    no_of_pixels = cv2.compare(threshold_image, 0, cv2.CMP_GT).sum() / 255
    if self.prevNoOfPixels is not None:
        if abs(self.prevNoOfPixels - no_of_pixels) / self.prevNoOfPixels > gamma:
            flag = True
    self.prevNoOfPixels = no_of_pixels
    return flag

I am guessing that cv2.compare(threshold_image, 0, cv2.CMP_GT).sum() is substracting an empty or 0 matrix from threshold image and storing it in a matrix that has something to do with cv2.CMP_GT .sum() is probably finding the number of pixels from that matrix. Am I right?

However, I couldn't find any official python documentation on the function cv2.compare() or on cv2.CMP_GT or on .sum() {used in such a way}. I did see that there are some articles on these keywords being used in C++. I will be grateful if someone can explain what these mean or share some documentation.

1 Answers

There is no subtraction taking place only comparison

cv2.compare performs an element-wise comparison. In simple words, given the following instance:

cv2.compare(a, b, cv2.CMP_GT)

every element in array A is compared with every element in array B. The flag cv2.CMP_GT is used to check whether the element in A is greater than of B in each comparison. It returns another array containing 0 and 255; where

  • 0 -> element in A is not greater than that in B
  • 255 -> element in A is greater than that in B

OpenCV limits the range between 0-255 internally.

In the following case:

cv2.compare(A, B, cv2.CMP_GT).sum()

it returns a scalar, the sum of all positions in array A where it is greater than that of array B

Illustration:

Consider an array:

A
array([[ 1,  2,  3],
       [-1, -2, -3],
       [ 4,  0,  0]])

compared with 0

cv2.compare(a, 0, cv2.CMP_GT)

returns 255 where elements in A are greater than 0:

array([[255, 255, 255],
       [  0,   0,   0],
       [255,   0,   0]], dtype=uint8)

The following would return number of positions where A is greater than 0:

cv2.compare(a, 0, cv2.CMP_GT).sum()/255

>>> 4.0

Other options:

Here are the list of flags that can be used:

  • CMP_EQ: equal to
  • CMP_GE: greater than or equal to
  • CMP_GT: greater than
  • CMP_LE: lesser than
  • CMP_LT: lesser than or equal to
  • CMP_NE: not equal to

Link to various flags used

Related