0

我使用 qrcode 扫描仪进行检测和解码,并正确解码输出。这里我使用“文本”作为 qrcode 的解码输出。如果它获得与 APPLE 相同类型的框,则必须将 apple_count 增加到 1。通过使用此代码,我只能为 apple_count 获得“1”。我认为问题可能是因为循环但我无法解决它。请帮助我。谢谢

class camera_1:

  def __init__(self):
    self.image_sub = rospy.Subscriber("/iris/usb_cam/image_raw", Image, self.callback)

  def callback(self,data):
    bridge = CvBridge()

    try:
      cv_image = bridge.imgmsg_to_cv2(data, "bgr8")
    except CvBridgeError as e:
      rospy.logerr(e)

    (rows,cols,channels) = cv_image.shape
    
    image = cv_image

    resized_image = cv2.resize(image, (640, 640)) 

    
    qr_result = decode(resized_image)

    #print (qr_result)
    
    qr_data = qr_result[0].data
    print(qr_data)
    
    (x, y, w, h) = qr_result[0].rect

    cv2.rectangle(resized_image, (x, y), (x + w, y + h), (0, 0, 255), 4)

    Apple_count = 0
    text = "{}".format(qr_data)
    type_of_box = (text.endswith("Apple"))    
    if type_of_box == True:
      Apple_count=Apple_count+1
    print(Apple_count)
    
4

1 回答 1

1

您的问题是因为您将局部变量更改为回调函数,而不是类属性。相反,您应该使用self关键字,以便计数器在多个回调中增加。

class camera_1:

  def __init__(self):
    self.Apple_count = 0
    self.image_sub = rospy.Subscriber("/iris/usb_cam/image_raw", Image, self.callback)

  def callback(self,data):
    bridge = CvBridge()

    try:
      cv_image = bridge.imgmsg_to_cv2(data, "bgr8")
    except CvBridgeError as e:
      rospy.logerr(e)

    (rows,cols,channels) = cv_image.shape
    
    image = cv_image

    resized_image = cv2.resize(image, (640, 640)) 

    
    qr_result = decode(resized_image)

    #print (qr_result)
    
    qr_data = qr_result[0].data
    print(qr_data)
    
    (x, y, w, h) = qr_result[0].rect

    cv2.rectangle(resized_image, (x, y), (x + w, y + h), (0, 0, 255), 4)

    text = "{}".format(qr_data)
    type_of_box = (text.endswith("Apple"))    
    if type_of_box == True:
      self.Apple_count += 1
    print(self.Apple_count)
    
于 2021-10-13T13:44:39.670 回答