def __init__(self, n_markers, marker_length, field_length, field_width, barrier_heigth, positions, ball, goal):
        markers_board = n_markers - 1  # n_markers includes marker for goal
        self.marker_ids = np.arange(1, n_markers)
        self.marker_list = [Marker(marker_length, positions[i]) for i in range(markers_board)]
        corner_ul = np.array([field_width, 0.0, barrier_heigth])
        corner_ur = np.array([field_width, field_length, barrier_heigth])
        corner_lr = np.array([0.0, field_length, barrier_heigth])
        corner_ll = np.array([0.0, 0.0, barrier_heigth])
        self.field_corners = np.array([[corner_ul], [corner_ur], [corner_lr], [corner_ll]])
        self.object_points = np.array([self.marker_list[i].corners for i in range(markers_board)], np.float32)
        self.ball = ball
        self.goal = goal

        self.dict = aruco.Dictionary_create(n_markers, 6)
        self.parameters = aruco.DetectorParameters_create()
        self.board = aruco.Board_create(self.object_points, self.dict, self.marker_ids)

        self.visible = False
        self.set = False
        self.ball_in_goal = False
        self.corners = None
        self.ids = None
        self.rvec = None
        self.tvec = None
        self.rot_mtx = None
        self.inv_rot_mtx = None
        self.inv_mtx = None
        self.tvec_camera = None
        self.roi_points = None
        self.radius_max = 250.0
        self.radius_min = 15.0
        self.tolerance = 0.1
Example #2
0
def createDict():
	# creates dictionary of markers based on marker bit arrays
	markers = aruco.Dictionary_create(bit_arrays.shape[0], bit_arrays.shape[1])
	byte_arrays = []
	for array in bit_arrays:
		byte_arrays.append(aruco.Dictionary_getByteListFromBits(array))
	bytesList = np.concatenate(byte_arrays, 0)
	markers.bytesList = bytesList
	return markers
Example #3
0
 def __init__(self, *args, **kwargs):
     """Set up all the required environment variables"""
     env_vars = [
         ("SDL_FBDEV", "/dev/fb1"),
         ("SDL_MOUSEDEV", "/dev/input/touchscreen"),
         ("SDL_MOUSEDRV", "TSLIB"),
     ]
     for var_name, val in env_vars:
         os.environ[var_name] = val
     self.timeout = kwargs.pop('timeout', 120)
     self.markers = aruco.Dictionary_create(6, 3)
Example #4
0
def generate_single():
    aruco_dict = aruco.Dictionary_create(1, 3)
    img = aruco.drawMarker(aruco_dict, 0, 1000)

    fig = plt.figure()
    fig.set_size_inches(10, 10)

    plt.imshow(img, cmap=plt.get_cmap("gray"), interpolation="nearest")
    plt.axis('off')

    plt.savefig("img/CustomDict_3x3_1/tag.png")
    plt.show()
Example #5
0
import sys
sys.path.append('/usr/local/lib/python2.7/site-packages')
import cv2
import numpy as np
import cv2.aruco as aruco
import dill

#small_dict = aruco.generateCustomDictionary(6, 3)
NUM_OF_MARKERS = 6
small_dict = aruco.Dictionary_create(NUM_OF_MARKERS, 3)
'''
    drawMarker(...)
        drawMarker(dictionary, id, sidePixels[, img[, borderBits]]) -> img
'''
#print ("created_dictionary.markerSize: %s" % small_dict.markerSize)
#print("created_dictionary: %s" % small_dict)
#data = {"mS": small_dict.markerSize, "mCB": small_dict.maxCorrectionBits, "bL": small_dict.bytesList}
#print data
#dill.dump(data,open("markers.dill", "wb"))

#new_data = dill.load(open('markers.dill', "rb"))
#print new_data
#loaded_dict = aruco.Dictionary_create(0, 3)
#loaded_dict.markerSize = new_data["mS"]
#loaded_dict.maxCorrectionBits = new_data["mCB"]
#loaded_dict.bytesList = new_data["bL"]

#loaded_dict = aruco.Dictionary(new_data["mS"], new_data["mCB"], new_data["bL"])

#print("saved and reloaded dictionary: %s" % loaded_dict)
#print("saved and reloaded dictionary.markerSize:" % loaded_dict.markerSize)
Example #6
0
import pickle
from cv2 import aruco
import cv2
import numpy as np

# arudict = aruco.Dictionary_get(pickle.load(f))
img1 = np.full((2970, 2100), 255, dtype=np.uint8)
arudict = aruco.Dictionary_create(8, 3)

side = 500


def draw_board(dict, start):
    img = np.full((1200, 1800), 255, dtype=np.uint8)
    cv2.rectangle(img, (1, 1), (1800, 1200), 220)
    cv2.line(img, (600, 0), (600, 1200), 220)
    cv2.line(img, (1200, 0), (1200, 1200), 220)
    aruco.drawMarker(dict, start + 0, side, img[50: 50 + side,
                                            900 - side // 2: 900 + side // 2])
    aruco.drawMarker(dict, start + 1, side, img[650: 650 + side,
                                            900 - side // 2: 900 + side // 2])
    aruco.drawMarker(dict, start + 2, side, img[600 - side // 2: 600 + side // 2,
                                            300 - side // 2: 300 + side // 2])
    aruco.drawMarker(dict, start + 3, side, img[600 - side // 2: 600 + side // 2,
                                            1500 - side // 2: 1500 + side // 2])
    return img


img = np.full((2970, 2100), 255, dtype=np.uint8)
img[200:200 + 1200, 150:150 + 1800] = draw_board(arudict, 0)
img[1570:1570 + 1200, 150:150 + 1800] = draw_board(arudict, 4)
Example #7
0
The image file is renamed using the tree number and orientation
'''

name = 'images/test_image.jpg'

parameters =  aruco.DetectorParameters_create()

# Load custom dictionary
dict_file = 'data/CUSTOM_ARUCO_MARKERS_DICT_8x8_512.pkl'

if os.path.isfile(dict_file):
    print ('Loading existing dictionary')
    with open(dict_file, 'rb') as fd:
          cdic_serializable = pickle.load(fd)

    cdic = aruco.Dictionary_create(5,3)
    cdic.markerSize = cdic_serializable['markerSize']
    cdic.maxCorrectionBits = cdic_serializable['maxCorrectionBits']
    cdic.bytesList = cdic_serializable['bytesList']
else:
    print ('ERROR: Could not read dictionary file!')
    sys.exit()

# Read test image
ima = cv2.imread(name)
gray = cv2.cvtColor(ima, cv2.COLOR_BGR2GRAY)
h,w = ima.shape[0:2]

corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, cdic, parameters=parameters)
print ('Markers found in image: ', ids)
Example #8
0
#  cap.set(cv2.CV_CAP_PROP_FOURCC, cv2.CV_FOURCC('M', 'J', 'P', 'G') );
#  cap.set(cv2.CAP_PROP_FRAME_WIDTH,1280)
#  cap.set(cv2.CAP_PROP_FRAME_HEIGHT,720)

#  print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
#  print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

while True:
        _,frame = cap.read()
        #  print(frame)
        #  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        gray = frame[:,:,0].astype(np.uint8)

        aruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_250)
        aruco_dict_one = aruco.Dictionary_create(1, 4)
        #  img = np.ones([500,500])
        #  img = np.full((500,500), 255, np.uint8)
        #  img = aruco.drawMarker(aruco_dict,50,200)
        img = aruco.drawMarker(aruco_dict_one,0,200)
        #  cv2.imshow("Marker", img)


        parameters =  aruco.DetectorParameters_create()
        #  corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict_one, parameters=parameters)
        corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters)
        #  frame_markers = gray
        #  frame_markers = aruco.drawDetectedMarkers(gray.copy(), corners, ids)
        gray_markers = aruco.drawDetectedMarkers(gray.copy(), corners, ids)

        if ids is not None:
import sys
import os
import cv2
from cv2 import aruco
from docopt import docopt
import pickle

if __name__ == '__main__':
    # read args
    args = docopt(__doc__)
    out_dir = args['<outDir>']

    dict_base = args['--dictBase']
    marker_size = int(args['--markerSize'])
    num_codes = int(args['--numCodes'])

    dict_file = '{od}/{dict_base}_{ms}x{ms}_{nm}.pkl'.format(
        od=out_dir, dict_base=dict_base, ms=marker_size, nm=num_codes)

    print('Creating new dictionary: {}'.format(dict_file))
    cdic = aruco.Dictionary_create(num_codes, marker_size)

    cdic_serializable = {}
    cdic_serializable['markerSize'] = cdic.markerSize
    cdic_serializable['maxCorrectionBits'] = cdic.maxCorrectionBits
    cdic_serializable['bytesList'] = cdic.bytesList

    with open(dict_file, 'wb') as fd:
        print('Saving dictionary as: {}'.format(dict_file))
        pickle.dump(cdic_serializable, fd)
Example #10
0
screen_width = 480
screen_centre = screen_width / 2
screen_height = 640

camera = picamera.PiCamera()
camera.resolution = (screen_width, screen_height)
camera.framerate = 30
camera.iso = 800
camera.shutter_speed = 12000
pygame.init()
screen = pygame.display.set_mode([240, 320])
video = picamera.array.PiRGBArray(camera)
drive = DriveTrain(timeout=120)

#create small cust dictionary
small_dict = aruco.Dictionary_create(6, 3)
print("setup complete, looking")
last_t_error = 0
speed = 0
MIN_SPEED = 0
MAX_SPEED = 1
STEERING_OFFSET = 0.0  #more positive make it turn left
STRAIGHT_TOLERANCE = 0.2
ACC_RATE = 0.2
CROP_WIDTH = 360
i = 0
TIMEOUT = 4.0
START_TIME = time.clock()
END_TIME = START_TIME + TIMEOUT
found = False
Example #11
0
Press SPACE when you're satisfied with the origin and axis.
The marker pose is saved in origin.npz."""

import cv2
import cv2.aruco as aruco
import numpy as np

# load the camera calibration parameters
calfile = np.load('calibration.npz')
newcameramtx = calfile['newcameramtx']
mtx = calfile['mtx']
dist = calfile['dist']
roi = calfile['roi']

# use a dictionary of 25 3x3 markers
aruco_dict = aruco.Dictionary_create(25, 3)

# size of the frames
width = 640
height = 480

# create the mappings to undistort the frames
map1, map2 = cv2.initUndistortRectifyMap(mtx, dist, None, None,
                                         (width, height), cv2.CV_32FC1)

# size of the origin marker
# the unit of this length will define the unit of the world frame coordinates
markerLength = 2.6  # 4.1

# start the capture (on camera channel 0)
cap = cv2.VideoCapture(0)
Example #12
0
import os
import sys
#sys.path.insert(0, '/usr/local/python/cv2')
sys.path.insert(0, '/usr/local/python/cv2/python-2.7/')

import numpy as np
import cv2

print cv2.__version__

import cv2.aruco as aruco

aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)
print aruco.DICT_6X6_250

test_dict = aruco.Dictionary_create(250, 6)
print test_dict.bytesList
sys.exit()

help(aruco)
sys.exit()

test_dict = aruco.custom_dictionary(250, 6)
print test_dict.bytesList
sys.exit()

#x = aruco.custom_dictionary_from(250, 36, "/home/abe/data/vision/mip36h12.dict")
#print x

#help(aruco_dict)
    marker_size = int(args['--markerSize'])
    num_codes = int(args['--numCodes'])
    num_markers = int(args['--numMarkers'])
    out_dir = args['--outDir']

    dict_file = '{dd}/{dict_base}_{ms}x{ms}_{nc}.pkl'.format(
        dd=data_dir, dict_base=dict_base, ms=marker_size, nc=num_codes)

    if os.path.isfile(dict_file):
        print('Loading existing dictionary: {}'.format(dict_file))
        with open(dict_file, 'rb') as fd:
            cdic_serializable = pickle.load(fd)

            cdic = aruco.Dictionary_create(
                5, 3
            )  # Create a small (i.e. fast) marker dictionary because I do not know how to create an empty dict.
            cdic.markerSize = cdic_serializable['markerSize']
            cdic.maxCorrectionBits = cdic_serializable['maxCorrectionBits']
            cdic.bytesList = cdic_serializable['bytesList']
    else:
        print('Dictionary file {} not found'.format(dict_file))
        sys.exit()

    #list_codes = [1, 100, 1000, 1965, 2001, 2019, 3003, 4004] # Change at will
    #list_codes = [4057, 3883,2883, 1711, 812, 351, 1, 0] # Change at will
    list_codes = np.random.randint(low=0, high=num_codes - 1, size=num_markers)

    marker_size_in_cm = 8
    resolution_inch_cm = 300
    num_pixels = int(round((marker_size_in_cm / 2.54) * resolution_inch_cm))
Example #14
0
    '-s',
    '--start',
    type=int,
    default=def_start,
    help='first marker to generate, default= {}'.format(def_start))
parser.add_argument('-e',
                    '--end',
                    type=int,
                    default=def_end,
                    help='last marker to generate default= {}'.format(def_end))
parser.add_argument('-v',
                    '--view',
                    action="store_true",
                    help='show marker on monitor')
args = parser.parse_args()

if args.dict == 99:  # use special 3x3 dictionary
    aruco_dict = aruco.Dictionary_create(32, 3)
else:
    aruco_dict = aruco.Dictionary_get(args.dict)
if args.end < args.start:
    args.end = args.start
#fig = plt.figure()
for i in range(args.start, args.end + 1):
    img = aruco.drawMarker(aruco_dict, i, 1000)
    plt.axis('off')
    plt.imshow(img, cmap=mpl.cm.gray, interpolation="nearest")
    plt.savefig("marker{}.png".format(i))
    if args.view:
        plt.show()
Example #15
0
    def __init__(self, args, params, parser):
        """ Initialize GcpFind object

            :param args: processed command line parameters
            :param params: aruco find param
            :param parser: parser object to print help
        """
        self.args = args
        # prepare aruco
        if args.dict == 99:     # use special 3x3 dictionary
            self.aruco_dict = aruco.Dictionary_create(32, 3)
        else:
            self.aruco_dict = aruco.Dictionary_get(args.dict)

        # set aruco parameters from command line arguments
        self.params = params
        self.params.detectInvertedMarker = args.inverted
        self.params.adaptiveThreshWinSizeMin = args.winmin
        self.params.adaptiveThreshWinSizeMax = args.winmax
        self.params.adaptiveThreshWinSizeStep = args.winstep
        self.params.adaptiveThreshConstant = args.thres
        self.params.minMarkerPerimeterRate = args.minrate
        self.params.maxMarkerPerimeterRate = args.maxrate
        self.params.polygonalApproxAccuracyRate = args.poly
        self.params.minCornerDistanceRate = args.corner
        self.params.minMarkerDistanceRate = args.markerdist
        self.params.minDistanceToBorder = args.borderdist
        self.params.markerBorderBits = args.borderbits
        self.params.minOtsuStdDev = args.otsu
        self.params.perspectiveRemovePixelPerCell = args.persp
        self.params.perspectiveRemoveIgnoredMarginPerCell = args.ignore
        self.params.maxErroneousBitsInBorderRate = args.error
        self.params.errorCorrectionRate = args.correct
        self.params.cornerRefinementMethod = args.refinement
        self.params.cornerRefinementWinSize = args.refwin
        self.params.cornerRefinementMaxIterations = args.maxiter
        self.params.cornerRefinementMinAccuracy = args.minacc
        if args.list:
            # list available aruco dictionary names & exit
            for act_dict in self.list_dicts():
                print('{} : {}'.format(act_dict[0], act_dict[1]))
            # list all aruco parameters
            for par in dir(self.params):
                if not par.startswith('__'):
                    val = getattr(self.params, par)
                    if type(val) in (int, float, str, bool):
                        print('{} : {}'.format(par, val))
            sys.exit(0)

        self.coords = {}
        self.gcp_found = {}          # initialize gcp to image dict
        if not self.check_params():
            parser.print_help()
            sys.exit(1)

        if self.args.input:
            # load GCP coords
            self.coo_input()

        if args.type == 'ODM' and args.epsg is not None:
            # write epsg code to the beginning of the output
            self.foutput.write('EPSG:{}\n'.format(args.epsg))
        # lookup table for color correction
        self.lut = np.interp(np.arange(0, 256), self.LUT_IN,
                             self.LUT_OUT).astype(np.uint8)