gpt4 book ai didi

python - 如何减少python中的多个if语句

转载 作者:行者123 更新时间:2023-12-05 08:35:53 24 4
gpt4 key购买 nike

我有以下代码片段:

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)

如您所见,我正在检查 i 的值并根据它选择合适的 hsv。有没有更好的方法通过避免多个 if 语句来做到这一点。谢谢

最佳答案

您可以使用包含 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)

关于python - 如何减少python中的多个if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71526214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com