Home > Software engineering >  How to reduce multiple if statement in python
How to reduce multiple if statement in python

Time:03-18

I have below code snippet:

amountLst = []
for i in range(9):
    hsv = ""
    if i == 0:
        hsv = cv2.cvtColor(barc0Img, cv2.COLOR_BGR2HSV)
    elif i == 1:
        hsv = cv2.cvtColor(barc1Img, cv2.COLOR_BGR2HSV)
    elif i == 2:
        hsv = cv2.cvtColor(barc2Img, cv2.COLOR_BGR2HSV)
    elif i == 3:
        hsv = cv2.cvtColor(barc3Img, cv2.COLOR_BGR2HSV)
    elif i == 4:
        hsv = cv2.cvtColor(barc4Img, cv2.COLOR_BGR2HSV)
    elif i == 5:
        hsv = cv2.cvtColor(barc5Img, cv2.COLOR_BGR2HSV)
    elif i == 6:
        hsv = cv2.cvtColor(barc6Img, cv2.COLOR_BGR2HSV)
    elif i == 7:
        hsv = cv2.cvtColor(barc7Img, cv2.COLOR_BGR2HSV)
    elif i == 8:
        hsv = cv2.cvtColor(barc8Img, cv2.COLOR_BGR2HSV)
    lower_bound = np.array([0, 80, 80])
    upper_bound = np.array([20, 255, 255])
    mask = cv2.inRange(hsv, lower_bound, upper_bound)
    amountLst.append(mask)

As you can see I am checking the value of i and based on it, selecting appropriate hsv. Is there a better way to do it by avoiding multiple if statement. Thanks

CodePudding user response:

You can use a list containing the barc<int>Img:

barcImg = [
    barc0Img,
    barc1Img,
    barc2Img,
    ...
]


amountLst = []
for i in range(9):
    hsv = cv2.cvtColor(barcImg[i], cv2.COLOR_BGR2HSV)
    lower_bound = np.array([0, 80, 80])
    upper_bound = np.array([20, 255, 255])
    mask = cv2.inRange(hsv, lower_bound, upper_bound)
    amountLst.append(mask)

CodePudding user response:

Start by putting your barcXImg references into a list:

barcImages = [barc0Img, barc1Img, barc2Img, barc3Img, barc4Img, barc5Img, barc6Img, barc7Img, barc8Img]

Calculate your upper and lower bounds just once (as they don't seem to have any dependency on anything else):

lo = np.array([0, 80, 80])
hi = np.array([20, 255, 255])

Then you can build your list with a comprehension:

amountLst = [cv2.inRange(cv2.cvtColor(img, cv2.COLOR_BGR2HSV), lo, hi) for img in barcImages]

CodePudding user response:

I suggest you to create a function that simulates switch-case

def switch(argument):
    switcher = {
        0: cv2.cvtColor(barc0Img, cv2.COLOR_BGR2HSV),
        1: cv2.cvtColor(barc1Img, cv2.COLOR_BGR2HSV),
        2: cv2.cvtColor(barc2Img, cv2.COLOR_BGR2HSV),
        3: cv2.cvtColor(barc3Img, cv2.COLOR_BGR2HSV),
        4: cv2.cvtColor(barc4Img, cv2.COLOR_BGR2HSV),
        5: cv2.cvtColor(barc5Img, cv2.COLOR_BGR2HSV),
        6: cv2.cvtColor(barc6Img, cv2.COLOR_BGR2HSV),
        7: cv2.cvtColor(barc7Img, cv2.COLOR_BGR2HSV),
        8: cv2.cvtColor(barc8Img, cv2.COLOR_BGR2HSV),
    }
    return switcher.get(argument, "nothing")

amountLst = []
argument = yourArgument  # 0,1,2,3,....
hsv = switch(argument)
lower_bound = np.array([0, 80, 80])
upper_bound = np.array([20, 255, 255])
mask = cv2.inRange(hsv, lower_bound, upper_bound)
amountLst.append(mask)
  • Related