Example #1
0
def calibration():
    calibrator = StereoCalibrator(rows, columns, square_size, image_size)

    print('Start processing')
    for i in range(1, 16):
        im_path_left = os.path.join(path, path2, left) + str(i) + ext
        im_path_right = os.path.join(path, path2, right) + str(i) + ext

        if os.path.exists(im_path_left) and os.path.exists(im_path_right):
            img_left = cv2.imread(im_path_left)
            img_right = cv2.imread(im_path_right)
        else:
            print(str(i) + ' step failed. Wrong path.')
            continue

        try:
            calibrator._get_corners(img_left)
            calibrator._get_corners(img_right)
        except ChessboardNotFoundError as error:
            print(error)
            print("Pair No " + str(i) + " ignored")
        else:
            calibrator.add_corners((img_left, img_right), True)
    print('End processing')

    calibration = calibrator.calibrate_cameras()
    calibration.export('D:\learn\8 sem\diplom\diplom\calib_result')
    print('Calibration complete!')
def calibrate_folder(args):
    """
    Calibrate camera based on chessboard images, write results to output folder.

    All images are read from disk. Chessboard points are found and used to
    calibrate the stereo pair. Finally, the calibration is written to the folder
    specified in ``args``.

    ``args`` needs to contain the following fields:
        input_files: List of paths to input files
        rows: Number of rows in chessboard
        columns: Number of columns in chessboard
        square_size: Size of chessboard squares in cm
        output_folder: Folder to write calibration to
    """
    print "file: " + args.input_files[0]
    height, width = cv2.imread(args.input_files[0]).shape[:2]
    calibrator = StereoCalibrator(args.rows, args.columns, args.square_size,
                                  (width, height))
    progress = ProgressBar(maxval=len(args.input_files),
                          widgets=[Bar("=", "[", "]"),
                          " ", Percentage()])
    print("Reading input files...")
    progress.start()
    while args.input_files:
        left, right = args.input_files[:2]

        print "processing: "
        print "    %s" %  left
        print "    %s" %  right
        print ""

        img_left, img_right = cv2.imread(left), cv2.imread(right)

        if img_left is not None and img_right is not None:
          calibrator.add_corners((img_left, img_right),
                                 show_results=args.show_chessboards)
          args.input_files = args.input_files[2:]
          progress.update(progress.maxval - len(args.input_files))
        else:
          print "error loading images."

    progress.finish()
    print("Calibrating cameras. This can take a while.")
    calibration = calibrator.calibrate_cameras()
    avg_error = calibrator.check_calibration(calibration)
    print("The average error between chessboard points and their epipolar "
          "lines is \n"
          "{} pixels. This should be as small as possible.".format(avg_error))
    calibration.export(args.output_folder)
Example #3
0
    def calibrate(self):
        rows = 6
        columns = 8
        square_size = 3
        image_size = (640, 480)

        path = 'resources/pictures/calibration_photos/'
        right = 'photo_right'
        left = 'photo_left'
        ext = '.jpg'

        calibrator = StereoCalibrator(rows, columns, square_size, image_size)

        #print('Start processing')
        for i in range(1, 16):
            im_path_left = os.path.join(path, left) + str(i) + ext
            im_path_right = os.path.join(path, right) + str(i) + ext

            if os.path.exists(im_path_left) and os.path.exists(im_path_right):
                img_left = cv2.imread(im_path_left)
                img_right = cv2.imread(im_path_right)
            else:
                print(str(i) + ' step failed. Wrong path.')
                continue

            try:
                calibrator._get_corners(img_left)
                calibrator._get_corners(img_right)
            except ChessboardNotFoundError as error:
                print(error)
                print("Pair No " + str(i) + " ignored")
            else:
                calibrator.add_corners((img_left, img_right), True)
        print('End processing')
        return
    def start_calibration(self):
        calibrator = StereoCalibrator(self.rows, self.columns,
                                      self.square_size,
                                      (self.img_width, self.img_height))
        photo_counter = 0
        print("Start calibration, press any key on image to move to the next")

        while photo_counter != self.total_photos:
            print('Import pair No ' + str(photo_counter))
            leftName = 'capture/pairs/left_' + str(photo_counter).zfill(
                2) + '.png'
            rightName = 'capture/pairs/right_' + str(photo_counter).zfill(
                2) + '.png'

            photo_counter = photo_counter + 1
            if os.path.isfile(leftName) and os.path.isfile(rightName):
                imgLeft = cv2.imread(leftName, 1)
                imgRight = cv2.imread(rightName, 1)
                try:
                    calibrator._get_corners(imgLeft)
                    calibrator._get_corners(imgRight)
                except ChessboardNotFoundError as error:
                    print(error)
                    print("Pair No " + str(photo_counter) + " ignored")
                else:
                    calibrator.add_corners((imgLeft, imgRight), True)

        print('End cycle')

        print('Starting calibration... It can take several minutes!')
        calibration = calibrator.calibrate_cameras()
        calibration.export('calibrate/calib_result')
        print('Calibration complete!')

        # Lets rectify and show last pair after  calibration
        calibration = StereoCalibration(input_folder='calibrate/calib_result')
        rectified_pair = calibration.rectify((imgLeft, imgRight))

        cv2.imshow('Left CALIBRATED', rectified_pair[0])
        cv2.imshow('Right CALIBRATED', rectified_pair[1])
        cv2.imwrite("calibrate/rectifyed_left.jpg", rectified_pair[0])
        cv2.imwrite("calibrate/rectifyed_right.jpg", rectified_pair[1])
        cv2.waitKey(0)
Example #5
0
def calibrate_folder(args):
    """
    Calibrate camera based on chessboard images, write results to output folder.

    All images are read from disk. Chessboard points are found and used to
    calibrate the stereo pair. Finally, the calibration is written to the folder
    specified in ``args``.

    ``args`` needs to contain the following fields:
        input_files: List of paths to input files
        rows: Number of rows in chessboard
        columns: Number of columns in chessboard
        square_size: Size of chessboard squares in cm
        output_folder: Folder to write calibration to
    """
    height, width = cv2.imread(args.input_files[0]).shape[:2]
    calibrator = StereoCalibrator(args.rows, args.columns, args.square_size,
                                  (width, height))
    progress = ProgressBar(maxval=len(args.input_files),
                           widgets=[Bar("=", "[", "]"), " ",
                                    Percentage()])
    print("Reading input files...")
    progress.start()
    while args.input_files:
        left, right = args.input_files[:2]
        img_left, im_right = cv2.imread(left), cv2.imread(right)
        calibrator.add_corners((img_left, im_right),
                               draw_results=args.show_chessboards)

        cv2.imshow("left_chessboard", img_left)
        cv2.imshow("right_chessboard", im_right)
        while True:
            key = cv2.waitKey(30) & 0xff
            if key == 27:  # esc
                break
        cv2.destroyWindow("left_chessboard")
        cv2.destroyWindow("right_chessboard")

        args.input_files = args.input_files[2:]
        progress.update(progress.maxval - len(args.input_files))

    progress.finish()
    print("Calibrating cameras. This can take a while.")
    calibration = calibrator.calibrate_cameras()
    avg_error = calibrator.check_calibration(calibration)
    print("The average error between chessboard points and their epipolar "
          "lines is \n"
          "{} pixels. This should be as small as possible.".format(avg_error))
    calibration.export(args.output_folder)
Example #6
0
from stereovision.exceptions import ChessboardNotFoundError

# Global variables preset
total_photos = 30
photo_width = 640
photo_height = 240
img_width = 320
img_height = 240
image_size = (img_width, img_height)

# Chessboard parameters
rows = 87
columns = 10
square_size = 2.5

calibrator = StereoCalibrator(rows, columns, square_size, image_size)
photo_counter = 0
print('Start cycle')

while photo_counter != total_photos:
    photo_counter = photo_counter + 1
    print('Import pair No ' + str(photo_counter))
    leftName = './pairs/left_' + str(photo_counter).zfill(2) + '.png'
    rightName = './pairs/right_' + str(photo_counter).zfill(2) + '.png'
    if os.path.isfile(leftName) and os.path.isfile(rightName):
        imgLeft = cv2.imread(leftName, 1)
        imgRight = cv2.imread(rightName, 1)
        try:
            calibrator._get_corners(imgLeft)
            calibrator._get_corners(imgRight)
        except ChessboardNotFoundError as error:
Example #7
0
from NEU_StereoPair import StereoPair
from stereovision.calibration import StereoCalibrator
import cv2

rows, colums = 9, 6
square_size = 2.4
image_size = (640, 480)

img_left = cv2.imread('./left.jpg')
img_right = cv2.imread('./right.jpg')

calibrator = StereoCalibrator(rows, colums, square_size, image_size)

calibrator.add_corners((img_left, img_right), show_results=True)
calibration = calibrator.calibrate_cameras()
print(calibration)

avg_error = calibrator.check_calibration(calibration)
print(avg_error)

calibration.export('./calibration_result')
columns = 9
square_size = 2.5


# Read pair cut parameters
f = open(params_file, "r")
data = json.load(f)
imageWidth = data["imageWidth"]
jointWidth = data["jointWidth"]
leftIndent = data["leftIndent"]
rightIndent = data["rightIndent"]
f.close()
image_size = (imageWidth, photo_Height)


calibrator = StereoCalibrator(rows, columns, square_size, image_size)
photo_counter = 0
print("Start cycle")

while photo_counter != total_photos:
    photo_counter = photo_counter + 1
    print("Import pair No " + str(photo_counter))
    leftName = "./pairs/left_" + str(photo_counter).zfill(2) + ".png"
    rightName = "./pairs/right_" + str(photo_counter).zfill(2) + ".png"
    if os.path.isfile(leftName) and os.path.isfile(rightName):
        imgLeft = cv2.imread(leftName, 1)
        imgRight = cv2.imread(rightName, 1)
        calibrator.add_corners((imgLeft, imgRight), True)
print("End cycle")

Example #9
0
    params.filterByCircularity = True
    params.minCircularity = 0.8

    # Filter by Convexity
    params.filterByConvexity = True
    params.minConvexity = 0.87

    # Filter by Inertia
    params.filterByInertia = True
    params.minInertiaRatio = 0.7

    #Blob detector parameters
    detector = cv2.SimpleBlobDetector_create(params)

#%%
calibrator = StereoCalibrator(rows, columns, square_size, image_size)
photo_counter = 0
print('Start cycle')

while photo_counter != total_photos:
    photo_counter = photo_counter + 1
    print('Import pair No ' + str(photo_counter))
    leftName = './gige_pairs/left_' + str(photo_counter).zfill(2) + '.bmp'
    rightName = './gige_pairs/right_' + str(photo_counter).zfill(2) + '.bmp'
    if os.path.isfile(leftName) and os.path.isfile(rightName):
        imgLeft = cv2.imread(leftName, 1)
        imgRight = cv2.imread(rightName, 1)
        try:
            if target_type == 'circle':
                calibrator.add_corners((imgLeft, imgRight),
                                       show_results=False,
Example #10
0
import os.path
import numpy as np
from stereovision.calibration import StereoCalibrator, StereoCalibration
from stereovision.blockmatchers import StereoBM, StereoSGBM
import cv2

calib_dir = './dataset_split_v2/CAM00054'
#if(not os.path.exists(calib_dir)):
calibrator = StereoCalibrator(8, 5, 2, (1536, 2048))
for idx in range(1, 14):
    calibrator.add_corners((cv2.imread(calib_dir+"_s1.jpg"), cv2.imread(calib_dir+"_s2.jpg")))


calibration = calibrator.calibrate_cameras()
print ("Calibation error:", calibrator.check_calibration(calibration))
calibration.export(calib_dir)

calibration = StereoCalibration(input_folder=calib_dir)

if True:
    block_matcher = StereoBM()
else:
    block_matcher = StereoSGBM()

for idx in range(1, 14):
    image_pair = (cv2.imread('images/left%02d.jpg' %idx), cv2.imread('images/right%02d.jpg' %idx))
    rectified_pair = calibration.rectify(image_pair)
    disparity = block_matcher.get_disparity(rectified_pair)
    norm_coeff = 255 / disparity.max()
    cv2.imshow('Disparity %02d' %idx, disparity * norm_coeff / 255)
Example #11
0
print ("Used camera resolution: "+str(cam_width)+" x "+str(cam_height))

# Buffer for captured image settings
img_width = int (cam_width * scale_ratio)
img_height = int (cam_height * scale_ratio)
capture = np.zeros((img_height, img_width, 4), dtype=np.uint8)
print ("Scaled image resolution: "+str(img_width)+" x "+str(img_height))

# Initialize the camera
camera = PiCamera(stereo_mode='side-by-side', stereo_decimate=False)
camera.resolution=(cam_width, cam_height)
camera.framerate = 5
camera.hflip = camera_hflip
camera.vflip = camera_vflip

calibrator = StereoCalibrator(rows, columns,
                              square_size, image_size)

# Lets start taking photos! 
counter = 0
t2 = datetime.now()
print ("Starting photo sequence")

all_left_corners = np.array([[0, 0]])
all_right_corners = np.array([[0, 0]])

for frame in camera.capture_continuous(capture, format="bgra", \
                  use_video_port=True, resize=(img_width,img_height)):
    t1 = datetime.now()
    cntdwn_timer = countdown - int ((t1-t2).total_seconds())
    # If cowntdown is zero - let's record next image
    if cntdwn_timer <= -1: