I found this code in blog about OpenCV and i rewrite for using ROS gazebo simulation. I got many error about marker`finding. I will add the error below.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from imutils import paths
import numpy as np
import imutils
import cv2
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class Camera():
def __init__(self):
rospy.init_node("camera_node")
self.bridge = CvBridge()
rospy.Subscriber("camera/rgb/image_raw", Image, self.cameraCallback)
self.distance_to_camera()
rospy.spin()
def cameraCallback(self, message):
try:
cv_image = self.bridge.imgmsg_to_cv2(message, desired_encoding="bgr8")
except Exception as e:
rospy.logerr("Error converting Image message to CV2: {}".format(e))
return None
# convert the image to grayscale, blur it, and detect edges
gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 35, 125)
# find the contours in the edged image and keep the largest one;
# we'll assume that this is our piece of paper in the image
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
if len(cnts) == 0:
rospy.logerr("No contour found in the image.")
return None
c = max(cnts, key=cv2.contourArea)
cv2.imshow("edged", edged)
cv2.imshow("camera", cv_image)
cv2.waitKey(1)
# compute the bounding box of the paper region and return it
return cv2.minAreaRect(c)
def distance_to_camera(self):
KNOWN_DISTANCE = 3
KNOWN_WIDTH = 0.3
image = cv2.imread("distance.png")
marker = self.cameraCallback(image)
if marker is None:
rospy.logerr("No marker found in the image.")
return
focalLength = (marker[1][0] * KNOWN_DISTANCE) / KNOWN_WIDTH
# compute and return the distance from the maker to the camera
# loop over the images
for imagePath in sorted(paths.list_images("images")):
# load the image, find the marker in the image, then compute the
# distance to the marker from the camera
image = cv2.imread(imagePath)
marker = self.cameraCallback(image)
inches = self.distance_to_camera(KNOWN_WIDTH, focalLength, marker[1][0])
# draw a bounding box around the image and display it
"""box = cv2.BoxPoints(marker) if imutils.is_cv2() else cv2.boxPoints(marker)
box = np.int0(box)
cv2.drawContours(image, [box], -1, (0, 255, 0), 2)
cv2.putText(image, "%.2fft" % (inches / 12),(image.shape[1] - 200, image.shape[0] - 20), cv2.FONT_HERSHEY_SIMPLEX,
2.0, (0, 255, 0), 3)"""
cv2.imshow("image", image)
cv2.waitKey(0)
if __name__ == '__main__':
# cam = Camera()
[ERROR] : Error converting Image message to CV2: 'numpy.ndarray' object has no attribute 'encoding'
[ERROR] : No marker found in the image.
Thank you...
I want to apply image process for camera id which is come to gazebo turtlebot3 waffle pi. Afetr the apply image process, i expect the robot camera detect the AR Tag and measure the distance between robot and AR Tag sticker.