What is | (Pipe) symbol used for in Python Opencv functions ( cv2.threshold)

I know this is Bitwise OR but what I want to know is what itis doing in the given function and how it works for function call

I have seen a couple of codes using | inside the opencv functions such as

t, im = cv2.threshold(blurred, 0, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)

What is the meaning of this |? What does is signifies and how can I use this | in a random function foo(x|y)?


You can create a function to use these values just as you would normally. BUT note it’s usual to define the constants being Or-ed so that each one sets only one bit when two or more values are OR-ed together.

In a function which would use these values, you would normally be testing eahc of the bots which is simplest done by AND-ing with the value, as in myfn() in the example below.

As someone else said in the asnwers, this style of bitwise OR-ing is/was common in C/C++ code implementations, and e.g. opencv python is a wrapper over the underlying opencv C++ implementation. Personally if I were designing a Python API I’d use separate named parameters for each flag, i.e. avoid the OR-ing.

For example:

import cv2

def showvalue(v):
    print( f"{v=} {bin(v)=} {hex(v)=}" )

showvalue( cv2.THRESH_OTSU )
showvalue( cv2.THRESH_BINARY_INV )
showvalue( cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU )

abit = 0b0010
bbit = 0b0100

def myfn( v ):
    print( "+++++++" )
    print( f"{v=}" )
    if v & abit:
        print( f"abit is set" )
    if v & bbit:
        print( f"bbit is set" )
    print( "-------" )

myfn(abit| bbit)


v=8 bin(v)='0b1000' hex(v)='0x8'
v=1 bin(v)='0b1' hex(v)='0x1'
v=9 bin(v)='0b1001' hex(v)='0x9'
abit is set
bbit is set
abit is set
bbit is set