if c == 1: # pallet
global pallet_center_x
distancei = (2 * 31.4 * 180) * 5 / (width + height)
plot_one_box(xyxy, im0, label=f'{distancei:.1f}cm', color=colors(c, True), line_thickness=2)
# x,y,w,h = cv2.boundingRect(xyxy)
# Draw circle in the center of the bounding box
pallet_x00 = int(x_top) # + int(width / 2)
pallet_y00 = int(y_top) # + int(height/2)
pallet_x01 = int(x_top + width)
pallet_y10 = int(y_top + height)
pallet_center_x = int((pallet_x01 + pallet_x00) / 2)
pallet_center_y = int((pallet_y00 + pallet_y10) / 2)
if c == 2: # pallet hole
hole_x00 = int(x_top) # + int(width / 2)
hole_y00 = int(y_top) # + int(height/2)
hole_x01 = int(x_top + width)
hole_y10 = int(y_top + height)
hole_centre_x = int((hole_x01 + hole_x00) / 2)
hole_centre_y = int((hole_y00 + hole_y10) / 2)
if hole_centre_x < pallet_center_x:
plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=2)
cv2.circle(im0, (hole_centre_x, hole_centre_y), 2, (0, 255, 0), -1) # center-point
# cv2.line(im0, (hole_centre_x, hole_centre_y), (pallet_center_x, pallet_center_y),
# (30, 255, 120), 1)
# cv2.line(im0, (hole_centre_x, hole_centre_y), (hole_centre_x, pallet_y10),
# (30, 255, 120),
# 1)
else:
pass我正在努力提取一个物体的坐标,并使用yolo算法绘制它的轮廓。
然而,有一个问题。
也就是说,在if c==1:中声明的pallet_center_x变量在if c==2:中没有引用。
错误内容如下。
Traceback (most recent call last):
File "C:/Users/KH/0802_doosan_ligdevice/210809_orange_ws/orange+green_0809test_workspace.py", line 643, in <module>
detect(**vars(opt))
File "C:\Python\Python36\lib\site-packages\torch\autograd\grad_mode.py", line 28, in decorate_context
return func(*args, **kwargs)
File "C:/Users/KH/0802_doosan_ligdevice/210809_orange_ws/orange+green_0809test_workspace.py", line 509, in detect
if hole_centre_x < pallet_center_x:
NameError: name 'pallet_center_x' is not defined
Process finished with exit code 1在if语句中声明的变量如何引用另一个if语句?
全局变量也不起作用。让我知道我做错了什么。
发布于 2021-08-10 11:28:19
您不需要使用global来引用variable。出现错误的原因是在定义variable pallet_center_x之前调用了它,因此您应该在调用pallet_center_x之前定义它。使用None作为占位符pallet_center_x = None
pallet_center_x = None
c = 2
if c == 1:
# lines of code
pallet_center_x = 1
elif c == 2:
if pallet_center_x == 1:
passhttps://stackoverflow.com/questions/68722722
复制相似问题