ArUco Marker Generation - Carleton-SRCL/SPOT GitHub Wiki

MarkerGenerator.py

Click here for raw code
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
import os

"""
Auto generates markers to be printed based on a specified dictionary for tracking
Written by Hayden Arms Sep 2023
"""

# Source: https://www.makeuseof.com/python-aruco-marker-generator-how-create/
# Dictionaries: https://docs.opencv.org/3.4/d9/d6a/group__aruco.html#ggac84398a9ed9dd01306592dd616c2c975a9f3ab829fb35fc9ff30e8f809d318e03

# MAIN
def main():
    print("OpenCV-Python Version:", cv.__version__)
    #  Marker Generation Param
    aruco_dict = cv.aruco.getPredefinedDictionary(cv.aruco.DICT_4X4_50)
    Method_Select = 2 # 1 == single, 2 == multiple
    Export = 1
    PltMarkers = 0
    ExportDir = r'/Directory'
    preDir = os.getcwd()

    if Method_Select == 1:
        marker_size = 200
        marker_id =  23 # marker ID for dictionary cv::aruco::DICT_6X6_250
        marker_img = generate_single_marker(aruco_dict,marker_size,marker_id,PltMarkers)
        if Export == 1:
            os.chdir(ExportDir)
            cv.imwrite("marker_{}.png".format(marker_id), marker_img)
            os.chdir(preDir)
    elif Method_Select == 2:
        marker_size = 200 # 200 x 200 pixel image
        num_markers = 9 # gen 3 markers
        out_mrkers = generate_bulk_markers(aruco_dict,marker_size,num_markers,PltMarkers)
        if Export == 1:
            os.chdir(ExportDir)
            for ind, item in enumerate(out_mrkers):
                cv.imwrite("marker_{}.png".format(ind), item)
            os.chdir(preDir)
    else:
        print("Invalid input. Please try again.")


# FUNCTIONS

def generate_single_marker(aruco_dict,marker_size,marker_id,pltTF):
    marker_img = cv.aruco.generateImageMarker(aruco_dict, marker_id, marker_size)
    # cv.imwrite("marker_{}.png".format(marker_id), marker_img)
    # marker_img = cv.imread("marker_{}.png".format(marker_id))
    print("Dimensions:", marker_img.shape)
    if pltTF == 1:
        plt
        plt.imshow(marker_img)
        plt.title('Generated Marker'), plt.xticks([]), plt.yticks([])
        plt.show()
    return marker_img

def generate_bulk_markers(aruco_dict,marker_size,num_markers,pltTF):
    marker_imgs = []
    for marker_id in range(num_markers):
        marker_img = cv.aruco.generateImageMarker(aruco_dict, marker_id, marker_size)
        # cv.imwrite("marker_{}.png".format(marker_id), marker_img)
        marker_imgs.append(marker_img)
    if pltTF == 1:
        _, axs = plt.subplots(num_markers, 1)
        for ind, item in enumerate(marker_imgs):
            print("Dimensions:", item.shape)
            axs[ind].imshow(item)
        plt.show()

    return marker_imgs

if __name__ == "__main__":
   main()


# GRAVEYARD

# testCanny = 0
# pathtoIm = "/Users/EightApplesJohnson/Desktop/Things/446.JPEG"

# # Canny Stuff
# img = cv.imread(pathtoIm, cv.IMREAD_GRAYSCALE)
# assert img is not None, "file could not be read, check with os.path.exists()"
# edges = cv.Canny(img,40,100)
# if testCanny == 1:
#     plt.subplot(121),plt.imshow(img,cmap = 'gray')
#     plt.title('Original Image'), plt.xticks([]), plt.yticks([])
#     plt.subplot(122),plt.imshow(edges,cmap = 'gray')
#     plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
#     plt.show()

Purpose

  • This function generates ArUco markers that can be printed and therefore used by cameras for pose detection.

Input Variables

  • aruco_dict
    • This is the dictionary that was selected for marker generation. The dictionary used in this project will be "cv.aruco.DICT_7X7_1000".
    • "DICT_7x7" refers to the size of the markers, in this case meaning that the ArUco marker will consist of a grid of 7x7 black and white squares.
    • With this sized grid, there are 1000 unique markers, which is where "1000" comes from.

Figure 2: 7x7 ArUco marker.

  • Method_Select

    • There are two methods to generating markers:
      1. Method 1 will generate a single marker.
      2. Method 2 will generate the specified amount of markers.
  • num_markers

    • This variable is only required if Method 2 of Method_Select is used.
    • The specified number of markers to generate is provided using this variable.

Figure 3: Generated ArUco output with a request of 9 markers.

  • Export

    • This variable determines the export type (either 1 or 0).
    • Setting to 1 will export the generated markers, otherwise they are not exported (ie. set to 0).
  • PltMarkers

    • This variable determines whether to plot the markers or not (either 1 or 0).
    • Setting to 1 will plot the generated markers, otherwise they are not plotted (ie. set to 0).
  • ExportDir

    • A Directory is required for the exported markers to be saved in, which is specified here.

Outputs

  • Depending on the specified values of Export and PltMarkers it will save the generated markers as .pngs to the specified directory and/or plot the markers.

Click here to go BACK

⚠️ **GitHub.com Fallback** ⚠️