我正在嘗試撰寫一個訂閱者,該訂閱者將在涼亭模擬中從相機拍攝影像并保存它們。我能夠拍照并保存它們,但是我每次都試圖增加影像名稱,但我發現這樣做很困難。我嘗試創建一個類,然后在每次運行 image_callback 函式時在類中增加一個數字 (image_number),但是我收到一個錯誤。我還嘗試定義一個全域變數并增加它,但它無法識別函式內部的變數。我附上了下面的代碼和錯誤,非常感謝任何幫助!
# rospy for the subscriber
import rospy, time
# ROS Image message
from sensor_msgs.msg import Image
# ROS Image message -> OpenCV2 image converter
from cv_bridge import CvBridge, CvBridgeError
# OpenCV2 for saving an image
import cv2
# Instantiate CvBridge
bridge = CvBridge()
class Image(object):
def __init__(self):
self.image_number = 0
#rospy.init_node('image_listener')
# Define your image topic
image_topic = "/wamv/sensors/cameras/front_left_camera/image_raw"
# Set up your subscriber and define its callback
rospy.Subscriber(image_topic, Image, self.image_callback)
#rospy.spin()
def image_callback(self, msg):
print("Received an image!")
try:
# Convert your ROS Image message to OpenCV2
cv2_img = bridge.imgmsg_to_cv2(msg, "bgr8")
except CvBridgeError as e:
print(e)
else:
# Save your OpenCV2 image as a jpeg
cv2.imwrite('croc_{}'.format(self.image_number) '.png', cv2_img)
print("Saved Image!")
self.image_number = 1
time.sleep(3.0)
if __name__ == '__main__':
rospy.init_node('image_listener')
image_node = Image()
和錯誤:
Traceback (most recent call last):
File "/home/jehan/PycharmProjects/spawner/take_photo.py", line 73, in <module>
image_node = Image()
File "/home/jehan/PycharmProjects/spawner/take_photo.py", line 54, in __init__
rospy.Subscriber(image_topic, Image, self.image_callback)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/topics.py", line 563, in __init__
super(Subscriber, self).__init__(name, data_class, Registration.SUB)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/topics.py", line 144, in __init__
raise ValueError("data_class [%s] is not a message data class"
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/363437.html
