我正在为我的机器人开发线检测功能。我试图组合 2 个不同的代码,因为第一个代码不适用于 ros。 我在
cv2.drawContours()
函数中遇到错误,我不知道如何禁用此问题
这是我的代码:
#! /usr/bin/env python
import rospy
import cv2
import numpy as np
from sensor_msgs.msg import Image
from sensor_msgs.msg import CompressedImage
from cv_bridge import CvBridge, CvBridgeError
import traceback
import sys
class LineDetector:
def __init__(self):
self.rate = rospy.Rate(rospy.get_param("/rate/lineDetector"))
self.bridge = CvBridge()
self.image_sub = rospy.Subscriber("/camera/image_raw", Image, self.image_callback_raw)
self.image_sub_rpi =rospy.Subscriber("/raspicam_node/image/compressed", CompressedImage, self.image_callback_compressed)
self.image_pub = rospy.Publisher("processed_image", Image, queue_size=1)
self.low_b =np.uint8([5,5,5])
self.high_b=np.uint8([0,0,0])
self.c=0
def image_callback_raw(self, msg):
try:
cv_image = self.bridge.imgmsg_to_cv2(msg, "passthrough")
self.process_image(cv_image)
except Exception as e:
traceback.print_exc()
rospy.logerr(e)
rospy.logerr("CvBridge Error, skipped image frame!")
def image_callback_compressed(self, msg):
try:
np_arr = np.frombuffer(msg.data, np.uint8)
image_np = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
self.process_image(image_np)
except Exception as e:
rospy.logerr(e)
rospy.logerr("skipped processed image frame!")
def process_image(self, cv_image):
mask=cv2.inRange(cv_image,self.low_b,self.high_b)
contours, hierarchy =cv2.findContours(mask, 1, cv2.CHAIN_APPROX_NONE)
if len(contours)>0:
self.c = max(contours, key=cv2.contourArea)
M = cv2.moments(self.c)
if M["m00"] != 0:
cx = int(M["m10"]/M['m00'])
cy = int(M["m01"]/M["m00"])
print("CX: "+str(cx)+" CY: "+str(cy))
if cx >= 120:
print("Turn Left")
if cx < 120 and cx > 40:
print ("On Track")
if cx <=40:
print("Turn Right")
cv2.circle(cv_image, (cx,cy), 5, (255,255,255), -1)
else:
print("I dont see the line")
cv2.drawContours(cv_image, self.c, -1,(0,255,0),-1)
image_message = self.bridge.cv2_to_imgmsg(cv_image, "passthrough")
self.image_pub.publish(image_message)
def run(self):
while not rospy.is_shutdown():
self.rate.sleep()
if __name__ == '__main__':
rospy.init_node('line_detector')
line_detector = LineDetector()
rospy.spin()
你知道如何实现c在drawcontours函数中工作吗?
真诚的帕斯卡
用轮廓切换 c.. 没有多大帮助