domenica 12 ottobre 2025

Migliorare Aruco Pose Estimantion con Deep Tag

Per cercare di migliorare i risultati di pose estimation di alcuni Aruco tag ho provato la rete neurale a questo link https://github.com/herohuyongtao/deeptag-pytorch 

Il progetto non funziona  ma bastano un paio di correzione e si adatta il codice a Python attuale

In blu la stima della pose estimation con OpenCv pura ed in rosso DeepTag 

I risultati risultano evidenti 





== configurazioene dei parametri di DeepTag

{
"is_video":0,
"filepath":"qui/20250929.jpg",
"family": "aruco",
"hamming_dist": 8,
"codebook": "",
"cameraMatrix": [2520.70396, 0, 1919.89817, 0, 2518.23371, 1022.39117, 0, 0, 1],
"distCoeffs": [ -0.39480147, 0.22634207, 0.00189933, 0.00101961, -0.08608824],
"marker_size": 0.25
}

===================================

Deeptag non comprende altre famiglie di Aruco Tag diverse da 5x5...io invece ho usato 4x4_250

per questo motivo ho modificato il file ./codebook/arucocodebook.txt

0,1,0,1,1,0,1,0,1,0,0,1,1,0,0,1,0
1,0,0,0,0,1,1,1,1,1,0,0,1,1,0,1,0
2,0,0,1,1,0,0,1,1,0,0,1,0,1,1,0,1
3,1,0,0,1,1,0,0,1,0,1,0,0,0,1,1,0
4,0,1,0,1,0,1,0,0,1,0,0,1,1,1,1,0
5,0,1,1,1,1,0,0,1,1,1,0,0,1,1,0,1
6,1,0,0,1,1,1,1,0,0,0,1,0,1,1,1,0
7,1,1,0,0,0,1,0,0,1,1,1,1,0,0,1,0
8,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,0
9,1,1,0,0,1,1,1,1,0,1,0,1,0,1,1,0
10,1,1,1,1,1,0,0,1,1,0,0,1,0,0,0,1
11,0,0,0,1,0,0,0,1,1,0,1,0,0,1,1,1
12,0,0,0,0,1,1,1,0,1,0,1,1,0,1,1,1
13,0,0,1,0,1,0,1,0,0,0,0,0,1,1,1,1
14,0,0,1,0,0,1,0,0,1,0,1,1,0,0,0,1
15,0,0,1,0,0,1,1,0,0,0,1,1,1,1,1,0
16,0,1,0,0,0,1,1,0,0,1,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0,0,0,0,1,0,1,0,1
228,0,1,1,0,0,0,0,1,1,1,0,0,0,0,1,0
229,0,1,1,0,1,0,1,1,0,0,1,0,0,0,0,0
230,0,1,1,0,0,0,1,1,0,1,0,0,0,1,0,1
231,0,1,1,0,1,0,1,1,0,1,0,1,1,1,0,0
232,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,1
233,0,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0
234,0,1,1,1,1,0,1,0,1,1,0,0,1,1,1,1
235,0,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1
236,0,1,1,1,1,0,0,1,1,0,0,0,0,0,0,0
237,0,1,1,1,0,0,0,1,1,1,1,0,0,1,0,1
238,0,1,1,1,0,0,0,1,0,1,1,1,0,1,0,0
239,0,1,1,1,1,0,0,1,1,0,1,1,0,1,1,0
240,0,1,1,1,0,0,0,1,1,1,0,1,0,0,1,1
241,0,1,1,1,1,0,1,1,0,0,1,1,0,0,1,1
242,0,1,1,0,0,1,0,0,0,1,1,0,1,0,1,0
243,0,1,1,0,0,1,1,0,1,0,1,0,1,0,0,0
244,0,1,1,0,1,1,1,0,1,0,1,0,0,1,1,1
245,0,1,1,0,1,1,1,0,1,0,0,1,0,0,0,1
246,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0
247,0,1,1,0,1,1,0,1,1,1,0,0,1,0,1,1
248,0,1,1,0,0,1,1,1,1,0,0,0,1,1,0,1
249,0,1,1,0,1,1,0,1,0,0,1,1,0,0,0,1


per crearsi il file in modo autonomo si puo' usare il codice

import cv2
import json
import numpy as np

aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_250)

codebook = {"family": "DICT_4X4_250", "markers": []}

for marker_id in range(250):
# Generate marker image (for verification)
marker_img = cv2.aruco.generateImageMarker(aruco_dict, marker_id, 200)

# Get binary pattern (4x4)
bits = aruco_dict.bytesList[marker_id][0]
bits = np.unpackbits(bits).reshape((4, 4)).astype(int).tolist()

codebook["markers"].append({
"id": int(marker_id),
"bits": bits
})

# Save to JSON
with open("aruco_4x4_250.json", "w") as f:
json.dump(codebook, f, indent=2)

===================================

#!/bin/bash
# Run DeepTag detection for all JPGs in ./qui

CONFIG="config_image.json"
FOLDER="./qui"

# Check if folder exists
if [ ! -d "$FOLDER" ]; then
echo "Error: folder '$FOLDER' not found!"
exit 1
fi

# Loop over all .jpg and .JPG files in folder
for img in "$FOLDER"/*.jpg "$FOLDER"/*.JPG; do
# Skip if no files found (glob didn't expand)
[ -e "$img" ] || continue

echo "Processing $img ..."
python test_deeptag.py --config "$CONFIG" --nome "$img"

# Optional: small delay to avoid CPU overload
# sleep 0.2
done

echo "✅ All images processed."

===================================

 import cv2

from deeptag_model_setting import load_deeptag_models
from marker_dict_setting import load_marker_codebook
from stag_decode.detection_engine import DetectionEngine
import json
import os
import numpy as np
import sys
import csv

if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str, default='./config_video.json', help='path of configuration file for camera params and marker size')
parser.add_argument('--CPU', action='store_true', help='use CPU only')
parser.add_argument('--nome', type=str, help='nomefile')
args = parser.parse_args()

config_filename = args.config
device = 'cpu' if args.CPU else None

# Load configuration
try:
config_dict = json.load(open(config_filename, 'r'))
cameraMatrix = config_dict['cameraMatrix']
distCoeffs = config_dict['distCoeffs']
tag_real_size_in_meter = config_dict['marker_size']
is_video = config_dict['is_video'] != 0
filename = config_dict['filepath']
tag_family = config_dict['family']
codebook_filename = (
config_dict['codebook']
if len(config_dict['codebook'])
else os.path.join('codebook', tag_family + '_codebook.txt')
)
hamming_dist = config_dict['hamming_dist']
except Exception as e:
print(f'Cannot load config: {config_filename} ({e})')
sys.exit(1)

if args.nome:
filename = args.nome

# Load models
try:
model_detector, model_decoder, device, tag_type, grid_size_cand_list = load_deeptag_models(tag_family, device)
except Exception as e:
print(f'Cannot load models: {e}')
sys.exit(1)

# Load marker library
try:
codebook = load_marker_codebook(codebook_filename, tag_type)
except Exception as e:
print(f'Cannot load codebook: {codebook_filename} ({e})')
sys.exit(1)

# Initialize detection engine
stag_image_processor = DetectionEngine(
model_detector, model_decoder, device, tag_type, grid_size_cand_list,
stg2_iter_num=2,
min_center_score=0.2, min_corner_score=0.2,
batch_size_stg2=4,
hamming_dist=hamming_dist,
cameraMatrix=cameraMatrix, distCoeffs=distCoeffs, codebook=codebook,
tag_real_size_in_meter_dict={-1: tag_real_size_in_meter}
)

# Read image
image = cv2.imread(filename)
if image is None:
print('Cannot read image.')
sys.exit(1)

decoded_tags = stag_image_processor.process(image, detect_scale=None)

# Prepare CSV
output_file = "risultato_tags.csv"
file_exists = os.path.exists(output_file)
date_str = filename[6:14] if len(filename) >= 14 else "unknown"

with open(output_file, 'a', newline='') as f:
writer = csv.writer(f)
#if not file_exists:
#writer.writerow(["other_id", "date", "dx", "dy", "dz", "distance_m"])

# Extract tvec for tag ID = 31
ref_tag = next((tag for tag in decoded_tags if tag.get('tag_id') == 11 and 'tvecs' in tag), None)

if ref_tag is None:
print("Tag ID 31 not found in this image.")
sys.exit(0)

ref_tvec = np.array(ref_tag['tvecs']).reshape(3)

# Compute relative distances to all other tags
for tag in decoded_tags:
if 'tvecs' in tag and tag['tag_id'] != 31:
other_tvec = np.array(tag['tvecs']).reshape(3)
diff = other_tvec - ref_tvec
distance = np.linalg.norm(diff)
writer.writerow([
tag['tag_id'], date_str,round(distance, 3)
])
#print(f"ID31 → ID{tag['tag_id']} : dx={diff[0]:.3f}, dy={diff[1]:.3f}, dz={diff[2]:.3f}, dist={distance:.3f}")
'''
overlay = image.copy()

for tag in decoded_tags:
tag_id = tag.get("tag_id", -1)

# Take first 4 keypoints as tag corners
corners = np.array(tag["keypoints_in_images"][:4], dtype=float)
corners = np.clip(corners, 0, [image.shape[1]-1, image.shape[0]-1]).astype(int)

# Compute center
center = np.mean(corners, axis=0).astype(int)

# Draw green outline
cv2.polylines(overlay, [corners], True, (0, 255, 0), 2, cv2.LINE_AA)

# Draw black rectangle behind text
text = f"ID:{tag_id}"
(text_w, text_h), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2)
cv2.rectangle(
overlay,
(center[0] - text_w // 2 - 4, center[1] - text_h // 2 - 10),
(center[0] + text_w // 2 + 4, center[1] + text_h // 2),
(0, 0, 0),
-1,
)

# Draw yellow tag ID
cv2.putText(
overlay, text,
(center[0] - text_w // 2, center[1] + text_h // 2 - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2, cv2.LINE_AA
)

# Blend overlay
disp = cv2.addWeighted(image, 0.7, overlay, 0.3, 0)

cv2.imshow("Detected Tags", disp)
print("Press any key to close...")
cv2.waitKey(0)
cv2.destroyAllWindows()
'''
sys.exit(0)


Nessun commento:

Posta un commento

Algoritmo Reed Solomon

 Sto progettando una trasmissione radio di immagini ed uno dei vincoli e' che non e' garantita la perfetta qualita' della trasmi...