Skip to content

Commit

Permalink
First edition
Browse files Browse the repository at this point in the history
First edition of OpenCV examples
  • Loading branch information
realizator committed Apr 4, 2019
1 parent fc86b5d commit f618baf
Show file tree
Hide file tree
Showing 121 changed files with 748 additions and 0 deletions.
85 changes: 85 additions & 0 deletions 1_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Copyright (C) 2019 Eugene Pomazov, <stereopi.com>, virt2real team
#
# This file is part of StereoPi tutorial scripts.
#
# StereoPi tutorial is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# StereoPi tutorial is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with StereoPi tutorial.
# If not, see <http://www.gnu.org/licenses/>.
#
# Most of this code is updated version of 3dberry.org project by virt2real
#
# Thanks to Adrian and http://pyimagesearch.com, as there are lot of
# code in this tutorial was taken from his lessons.
#


import picamera
from picamera import PiCamera
import time
import cv2
import numpy as np
import os
from datetime import datetime


# File for captured image
filename = './scenes/photo.png'

# Camera settimgs
cam_width = 1280
cam_height = 480

# Final image capture settings
scale_ratio = 0.5

# Camera resolution height must be dividable by 16, and width by 32
cam_width = int((cam_width+31)/32)*32
cam_height = int((cam_height+15)/16)*16
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 = 20
camera.hflip = True


t2 = datetime.now()
counter = 0
avgtime = 0
# Capture frames from the camera
for frame in camera.capture_continuous(capture, format="bgra", use_video_port=True, resize=(img_width,img_height)):
counter+=1
t1 = datetime.now()
timediff = t1-t2
avgtime = avgtime + (timediff.total_seconds())
cv2.imshow("pair", frame)
key = cv2.waitKey(1) & 0xFF
t2 = datetime.now()
# if the `q` key was pressed, break from the loop and save last image
if key == ord("q") :
avgtime = avgtime/counter
print ("Average time between frames: " + str(avgtime))
print ("Average FPS: " + str(1/avgtime))
if (os.path.isdir("./scenes")==False):
os.makedirs("./scenes")
cv2.imwrite(filename, frame)
break


92 changes: 92 additions & 0 deletions 2_chess_cycle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Copyright (C) 2019 Eugene Pomazov, <stereopi.com>, virt2real team
#
# This file is part of StereoPi tutorial scripts.
#
# StereoPi tutorial is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# StereoPi tutorial is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with StereoPi tutorial.
# If not, see <http://www.gnu.org/licenses/>.
#
# Most of this code is updated version of 3dberry.org project by virt2real
#
# Thanks to Adrian and http://pyimagesearch.com, as there are lot of
# code in this tutorial was taken from his lessons.
#

import os
import time
from datetime import datetime
import picamera
from picamera import PiCamera
import cv2
import numpy as np

# Photo session settings
total_photos = 30 # Number of images to take
countdown = 5 # Interval for count-down timer, seconds
font=cv2.FONT_HERSHEY_SIMPLEX # Cowntdown timer font

# Camera settimgs
cam_width = 1280 # Cam sensor width settings
cam_height = 480 # Cam sensor height settings

# Final image capture settings
scale_ratio = 0.5

# Camera resolution height must be dividable by 16, and width by 32
cam_width = int((cam_width+31)/32)*32
cam_height = int((cam_height+15)/16)*16
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 = 20
camera.hflip = True

# Lets start taking photos!
counter = 0
t2 = datetime.now()
print ("Starting photo sequence")
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:
counter += 1
filename = './scenes/scene_'+str(img_width)+'x'+str(img_height)+'_'+\
str(counter) + '.png'
cv2.imwrite(filename, frame)
print (' ['+str(counter)+' of '+str(total_photos)+'] '+filename)
t2 = datetime.now()
time.sleep(1)
cntdwn_timer = 0 # To avoid "-1" timer display
next
# Draw cowntdown counter, seconds
cv2.putText(frame, str(cntdwn_timer), (50,50), font, 2.0, (0,0,255),4, cv2.LINE_AA)
cv2.imshow("pair", frame)
key = cv2.waitKey(1) & 0xFF

# Press 'Q' key to quit, or wait till all photos are taken
if (key == ord("q")) | (counter == total_photos):
break


print ("Photo sequence finished")

60 changes: 60 additions & 0 deletions 3_pairs_cut.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Copyright (C) 2019 Eugene Pomazov, <stereopi.com>, virt2real team
#
# This file is part of StereoPi tutorial scripts.
#
# StereoPi tutorial is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# StereoPi tutorial is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with StereoPi tutorial.
# If not, see <http://www.gnu.org/licenses/>.
#
# Most of this code is updated version of 3dberry.org project by virt2real
#
# Thanks to Adrian and http://pyimagesearch.com, as there are lot of
# code in this tutorial was taken from his lessons.
#


import cv2
import os

# Global variables preset
total_photos = 30
photo_width = 640
photo_height = 240
img_height = 240
img_width = 320
photo_counter = 0


# Main pair cut cycle
if (os.path.isdir("./pairs")==False):
os.makedirs("./pairs")
while photo_counter != total_photos:
photo_counter +=1
filename = './scenes/scene_'+str(photo_width)+'x'+str(photo_height)+\
'_'+str(photo_counter) + '.png'
if os.path.isfile(filename) == False:
print ("No file named "+filename)
continue
pair_img = cv2.imread(filename,-1)

cv2.imshow("ImagePair", pair_img)
cv2.waitKey(0)
imgLeft = pair_img [0:img_height,0:img_width] #Y+H and X+W
imgRight = pair_img [0:img_height,img_width:photo_width]
leftName = './pairs/left_'+str(photo_counter).zfill(2)+'.png'
rightName = './pairs/right_'+str(photo_counter).zfill(2)+'.png'
cv2.imwrite(leftName, imgLeft)
cv2.imwrite(rightName, imgRight)
print ('Pair No '+str(photo_counter)+' saved.')

print ('End cycle')
11 changes: 11 additions & 0 deletions 3dmap_set.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"SADWindowSize":9,
"minDisparity":4,
"numberOfDisparities":32,
"preFilterCap":27,
"preFilterSize":9,
"speckleRange":0,
"speckleWindowSize":0,
"textureThreshold":11,
"uniquenessRatio":1
}
86 changes: 86 additions & 0 deletions 4_calibration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Copyright (C) 2019 Eugene Pomazov, <stereopi.com>, virt2real team
#
# This file is part of StereoPi tutorial scripts.
#
# StereoPi tutorial is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# StereoPi tutorial is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with StereoPi tutorial.
# If not, see <http://www.gnu.org/licenses/>.
#
# Most of this code is updated version of 3dberry.org project by virt2real
#
# Thanks to Adrian and http://pyimagesearch.com, as there are lot of
# code in this tutorial was taken from his lessons.
#

import os
import cv2
import numpy as np
import json
from stereovision.calibration import StereoCalibrator
from stereovision.calibration import StereoCalibration
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 = 6
columns = 9
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:
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('calib_result')
print ('Calibration complete!')


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

cv2.imshow('Left CALIBRATED', rectified_pair[0])
cv2.imshow('Right CALIBRATED', rectified_pair[1])
cv2.imwrite("rectifyed_left.jpg",rectified_pair[0])
cv2.imwrite("rectifyed_right.jpg",rectified_pair[1])
cv2.waitKey(0)
Loading

0 comments on commit f618baf

Please sign in to comment.