Распознавание двухмерных штрихкодов ArUco в TXT4.0

Обсуждаем модели и конструкции, построенные своими руками
Ответить
Вася М.
Сообщения: 26
Зарегистрирован: 20 дек 2010, 19:28

Распознавание двухмерных штрихкодов ArUco в TXT4.0

Сообщение Вася М. »

Всем привет!

Подскажите, пожалуйста - как можно реализовать в контроллере TXT4.0 распознавание двухмерных штрихкодов ArUco в реальном времени? Может быть эту задачу можно решить с помощью библиотеки компьютерного зрения OpenCV, которая есть на борту у контроллера. Я планирую использовать эти штрихкоды для локализация робота Fischertechnik в закрытом пространстве.

Пример штрихкода c ID=57 из словаря 4x4:
image.png
image.png (1.88 КБ) 7350 просмотров
Последний раз редактировалось Вася М. 04 фев 2022, 10:03, всего редактировалось 1 раз.
IDKFA!
Аватара пользователя
Mr.Kubikus
Сотрудник ПАКПАК
Сообщения: 1018
Зарегистрирован: 22 окт 2010, 23:57

Re: Распознавание двухмерных штрихкодов ArUco в TXT4.0

Сообщение Mr.Kubikus »

Здравствуйте!

Да, это можно сделать на контроллере TXT4.0.

В текущей версии 3.1.0 прошивки контроллера TXT4.0 имеется библиотека OpenCV версии 4.1.0:

Код: Выделить всё

$ opencv_version -v | grep OpenCV
General configuration for OpenCV 4.1.0 =====================================
В конфигурацию библиотеки входит модуль aruco:

Код: Выделить всё

$ opencv_version -v | grep aruco
    To be built:                 aruco bgsegm bioinspired calib3d ccalib core datasets dpm face features2d flann fuzzy gapi hfs highgui img_hash imgcodecs imgproc line_descriptor ml objdetect optflow phase_unwrapping photo plot python3 quality reg rgbd saliency shape stereo stitching structured_light superres surface_matching tracking ts video videoio videostab xfeatures2d ximgproc xobjdetect xphoto
С этим модулем можно работать из программы, написанной на питоне. Ниже исходный код программы detect_aruco_cam.py, которая выполняется на контроллере Fischertechnik TXT4.0. Программа detect_aruco_cam.py запускается из командной строки:

Код: Выделить всё

$ python3 detect_aruco_cam.py --type DICT_4X4_100
Параметр --type используется для настройки словаря. Возможные варианты можно посмотреть в исходном коде.

Код: Выделить всё

#!/usr/bin/env python

# python detect_aruco_image.py --image images/example_01.png --type DICT_4X4_100

# import the necessary packages
import argparse
import imutils
import cv2
import sys

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-t", "--type", type=str,
	default="DICT_4X4_100",
	help="type of ArUCo tag to detect")
args = vars(ap.parse_args())

# open camera
videoCapture = cv2.VideoCapture(0)
if not videoCapture.isOpened():
    print("[ERROR]Cannot open camera")
    exit()

# define names of each possible ArUco tag OpenCV supports
ARUCO_DICT = {
	"DICT_4X4_100": cv2.aruco.DICT_4X4_100,
	"DICT_5X5_100": cv2.aruco.DICT_5X5_100,
	"DICT_5X5_1000": cv2.aruco.DICT_5X5_1000
}

# capture input image from camera and resize it
print("[INFO] Capturing image...")

success, image = videoCapture.read()
if not success:
    print("[ERROR]Cannot capture image from camera")
    exit()

success = cv2.imwrite("filename-raw.jpg",image)
image = imutils.resize(image, width=600)


# verify that the supplied ArUCo tag exists and is supported by
# OpenCV
if ARUCO_DICT.get(args["type"], None) is None:
	print("[INFO] ArUCo tag of '{}' is not supported".format(args["type"]))
	sys.exit(0)

# load the ArUCo dictionary, grab the ArUCo parameters, and detect
# the markers
print("[INFO] detecting '{}' tags...".format(args["type"]))
arucoDict = cv2.aruco.Dictionary_get(ARUCO_DICT[args["type"]])
arucoParams = cv2.aruco.DetectorParameters_create()
(corners, ids, rejected) = cv2.aruco.detectMarkers(image, arucoDict,
	parameters=arucoParams)

# verify *at least* one ArUco marker was detected
if len(corners) > 0:
	# flatten the ArUco IDs list
	ids = ids.flatten()

	# loop over the detected ArUCo corners
	for (markerCorner, markerID) in zip(corners, ids):
		# extract the marker corners (which are always returned in
		# top-left, top-right, bottom-right, and bottom-left order)
		corners = markerCorner.reshape((4, 2))
		(topLeft, topRight, bottomRight, bottomLeft) = corners

		# convert each of the (x, y)-coordinate pairs to integers
		topRight = (int(topRight[0]), int(topRight[1]))
		bottomRight = (int(bottomRight[0]), int(bottomRight[1]))
		bottomLeft = (int(bottomLeft[0]), int(bottomLeft[1]))
		topLeft = (int(topLeft[0]), int(topLeft[1]))

		# draw the bounding box of the ArUCo detection
		cv2.line(image, topLeft, topRight, (0, 255, 0), 2)
		cv2.line(image, topRight, bottomRight, (0, 255, 0), 2)
		cv2.line(image, bottomRight, bottomLeft, (0, 255, 0), 2)
		cv2.line(image, bottomLeft, topLeft, (0, 255, 0), 2)

		# compute and draw the center (x, y)-coordinates of the ArUco
		# marker
		cX = int((topLeft[0] + bottomRight[0]) / 2.0)
		cY = int((topLeft[1] + bottomRight[1]) / 2.0)
		cv2.circle(image, (cX, cY), 4, (0, 0, 255), -1)

		# draw the ArUco marker ID on the image
		cv2.putText(image, str(markerID),
			(topLeft[0], topLeft[1] - 15), cv2.FONT_HERSHEY_SIMPLEX,
			0.5, (0, 255, 0), 2)
		print("[INFO] ArUco marker ID: {}".format(markerID))

		# show the output image
		# cv2.imshow("Image", image)

		# write output image
		print("[INFO] write result image...")
		success = cv2.imwrite("filename-result.jpg",image)

videoCapture.release()
После запуска выполняется захват изображения от подключенной usb-камеры Fischertechnik 152522. Затем программа уменьшает размер изображения до 600 пикселей по ширине и запускает распознавание маркеров ArUco из указанного в параметрах запуска словаря. Можно выбрать DICT_4X4_100 или DICT_5X5_100. Результат распознавания выводится на экран в виде списка идентификаторов и одновременно сохраняется в файл filename-result.jpg

Результат, полученный для вашего штрихкода ArUco:
image.png
image.png (304.12 КБ) 7349 просмотров
Программа основана на коде detect_aruco_image.py из репозитария на github.
С уважением, Григорий
GitHub FB ВК
Ответить