SlideShare a Scribd company logo
INTRODUCTION TO OPENCV
HANDS-ON WORKSHOP IN PYTHON
Amit Mandelbaum
TIP 2016, Jerusalem
mangate@gmail.com
OVERVIEW
 OpenCV is the most popular Image Processing and
Computer Vision library
 Free for both academic and commercial use
 Very easy to learn
 It has C++, C, Python and Java interfaces and supports
Windows, Linux, Mac OS, iOS and Android
 Designed for computational efficiency and with a strong
focus on real-time applications
 Lot of documentation online
RESOURCES
 Official site: http://opencv.org/
 Tutorials
 http://docs.opencv.org/3.0-
beta/doc/py_tutorials/py_tutorials.html (official, python)
 http://docs.opencv.org/2.4/doc/tutorials/tutorials.html
(official c++)
 https://opencv-python-tutroals.readthedocs.io/en/latest/
(python)
 http://opencvexamples.blogspot.com/ (c++)
 http://www.pyimagesearch.com/ (some cool free
advanced tutorials)
 Google
WORKSHOP OUTLINE (TOPICS)
 Loading, showing and saving images
 Histograms and Histograms equalizations
 Gamma correction
 Smoothing, sharpening and noise removal
 Morphological operations (erosion, dilation)
 Edge detection
 Transformation
 Adaptive thresholding
 And finally: Document scanner
LOADING, SHOWING AND SAVING IMAGES
 Loading: image = cv2.imread(“file_name",0)
(0 means Gray Scale, no number will use original
image’s colors)
 Displaying: cv2.imshow(“some headline",image)
(Usually followed by: cv2.waitKey(0) so the image
will not close immediately)
 Saving: cv2.imwrite(“file_name",image)
 Code: load_and_display.py
HISTOGRAMS AND HISTOGRAMS EQUALIZATIONS
 Histogram: Showing how many pixels have a
certain intensity (between 0 and 255) in a picture.
HISTOGRAMS AND HISTOGRAMS
EQUALIZATIONS (CONT.)
 “Good” pictures have their histograms nearly
equally spread over the entire range.
 However in a lot of pictures this is not always the
case
HISTOGRAMS AND HISTOGRAMS
EQUALIZATIONS (CONT.)
 Solution: Histogram equalization
(see theoretical equations here:
http://www.math.uci.edu/icamp/courses/math77c/demos/hist_eq.pdf)
 With openCV: image2 = cv2.equalizeHist(image)
Code:
load_and_display.py
HISTOGRAMS AND HISTOGRAMS
EQUALIZATIONS (CONT.)
 On color images:
 Split the color channels with: b,g,r = cv2.split(image)
 Equalize each channel separately
 Merge the channels with: image2 = cv2.merge((b,g,r))
 Code: equalizing_color_images.py
GAMMA CORRECTION
 Sometimes images are too dark, or too bright
 Fixing it with just adding/substracting intensities
produses bad results
 Solution: Gamma correction
 Transform intensities from [0,255] to [0,1] with a LUT
(look up table)
 Apply this to all pixels: O = I ^ (1 / G) (G is the gamma
value, higher = brighter)
 Transform back to [0,255] with LUT
GAMMA CORRECTION (CONT.)
 In openCV:
def adjust_gamma(image, gamma=1.0):
invGamma = 1.0 / gamma
table = np.array([((i / 255.0) ** invGamma) * 255
for i in np.arange(0, 256)]).astype("uint8")
return cv2.LUT(image, table)
adjusted = adjust_gamma(original, gamma=2)
Code:
gamma_correction.py
SMOOTHING, SHARPENING AND NOISE REMOVAL
 Smoothing is done by applying a simple filter to the picture, for
example (3x3 kernel):
Each pixel is averaged with its 8 neighbors.
 Gaussian smoothing : Each pixel is averaged (with Gaussian
weights) with its 8 neighbors.
 Median smoothing: Each pixel is gets the median value of him
and its 8 neighbors.
SMOOTHING, SHARPENING AND NOISE
REMOVAL (CONT.)
 In openCV (5x5 kernel:
 average_blur = cv2.blur(image,(5,5))
 gaussian = cv2.GaussianBlur(image,(5,5),0)
 median = cv2.medianBlur(image,5)
Code:
smoothing _and_cleaning.py
SMOOTHING, SHARPENING AND NOISE
REMOVAL (CONT.)
 Sharpening: Done be subtracting from the picture, a Gaussian
blurred version of itself
 In openCV:
gaussian = cv2.GaussianBlur(image,(9,9),10)
sharpened = cv2.addWeighted(image,1.5,gassuian,-0.5,0)
Code:
smoothing _and_cleaning.py
SMOOTHING, SHARPENING AND NOISE
REMOVAL (CONT.)
 Some types of noise (especially Salt & Pepper) can
be removed by using a median filter (with a small
kernel)
Code:
smoothing _and_cleaning.py
MORPHOLOGICAL OPERATIONS (EROSION,
DILATION)
 Morphological transformations are some simple operations
based on the image shape.
 It is normally performed on binary images.
 It needs two inputs, one is our original image, second one is
called structuring element or kernel which decides the
nature of operation.
 Two basic morphological operators are Erosion and Dilation
 Erosion: Match the value of all pixels in the kernel to the one
with the minimum value .
 Dilation: Match the value of all pixels in the kernel to the one
with the maximum value .
MORPHOLOGICAL OPERATIONS (EROSION,
DILATION) (CONT.)
 On openCV (with kernel of 5x5):
kernel = np.ones((5,5),np.uint8)
eroded = cv2.erode(image,kernel)
dilated = cv2.dilate(image,kernel)
Original Eroded
Dilated
Code:
erosion_dialation_inversion.py
EDGE DETECTION (CANNY)
 Canny Edge Detection is a popular edge detection algorithm. It was
developed by John F. Canny in 1986
 Does the following steps:
 Cleaning the image by blurring it.
 Finding Intensity Gradient of the Image:
Using Sobel to find intensities of gradients in x and y directions creates a
picture of gradient intensities.
 Non-maximum Suppression:
Suppress (set to 0) all pixels which are not a local maximum, to thin the
edges.
 Hysteresis Thresholding:
Any edges with intensity gradient more than maxVal are sure to be edges
and those below minVal are sure to be non-edges, so discarded. Those
who lie between these two thresholds are classified edges or non-edges
based on their connectivity. If they are connected to “sure-edge” pixels,
they are considered to be part of edges. Otherwise, they are also
discarded
EDGE DETECTION (CANNY) (CONT.)
 In openCV:
edges = cv2.Canny(img,100,200)
(The two numbers are min-val and max-val)
Code: edge_detection.py
TRANSFORMATION
 Transformation: Reshape the picture such that is gets 4 co-ordinates from
the original picture and 4 new coordinates, and trasnforms the picture so the
4 points (and all points between them) will match the new ones.
 In openCV :
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(257,259))
(The last two numbers are the size of the new image)
Code: trasnformation_and_adaptive_threshold.py
ADAPTIVE THRESHOLDING
 Thresholding: Set pixel to 255 if it’s intensity is above a
certain threshold, otherwise set to 0.
 Simple thresholding: Threshold is constant for the entire
picture.
 Adaptive thresholding: Different thresholds for different
regions of the same image
 Mean: Threshold value is the mean of neighborhood area.
 Gaussian: Threshold value is the weighted sum of
neighborhood values where weights are a Gaussian
window.
ADAPTIVE THRESHOLDING (CONT.)
 In openCV:
ret,th1 = cv2.threshold(dst,127,255,cv2.THRESH_BINARY)
th2 =
cv2.adaptiveThreshold(dst,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
th3 =
cv2.adaptiveThreshold(dst,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
Code:
trasnformation_and_adaptiv
e_threshold.py
DOCUMENT SCANNER
 Steps:
 Edge detection
 Contour (find borders
 Transformation (So only document remains)
 Adaptive thresholding
 Code: scan.py
DOCUMENT SCANNER (CONT.)
Original Edge detection Contour Transformation and
Thresholding
Thank you!

More Related Content

What's hot

Computer Vision image classification
Computer Vision image classificationComputer Vision image classification
Computer Vision image classification
Wael Badawy
 
Object Detection using Deep Neural Networks
Object Detection using Deep Neural NetworksObject Detection using Deep Neural Networks
Object Detection using Deep Neural Networks
Usman Qayyum
 
Introduction to object detection
Introduction to object detectionIntroduction to object detection
Introduction to object detection
Brodmann17
 
An Introduction to Computer Vision
An Introduction to Computer VisionAn Introduction to Computer Vision
An Introduction to Computer Vision
guestd1b1b5
 
Image Processing and Computer Vision
Image Processing and Computer VisionImage Processing and Computer Vision
Image Processing and Computer Vision
Silicon Mentor
 
CNN Tutorial
CNN TutorialCNN Tutorial
CNN Tutorial
Sungjoon Choi
 
Deep learning for object detection
Deep learning for object detectionDeep learning for object detection
Deep learning for object detection
Wenjing Chen
 
Object detection
Object detectionObject detection
Object detection
ROUSHAN RAJ KUMAR
 
Computer vision introduction
Computer vision  introduction Computer vision  introduction
Computer vision introduction
Wael Badawy
 
Application of edge detection
Application of edge detectionApplication of edge detection
Application of edge detection
Naresh Biloniya
 
[PR12] You Only Look Once (YOLO): Unified Real-Time Object Detection
[PR12] You Only Look Once (YOLO): Unified Real-Time Object Detection[PR12] You Only Look Once (YOLO): Unified Real-Time Object Detection
[PR12] You Only Look Once (YOLO): Unified Real-Time Object Detection
Taegyun Jeon
 
Introduction to Object recognition
Introduction to Object recognitionIntroduction to Object recognition
Introduction to Object recognition
Ashiq Ullah
 
Computer vision - images and image filtering
Computer vision - images and image filtering Computer vision - images and image filtering
Computer vision - images and image filtering
Wael Badawy
 
Object detection
Object detectionObject detection
Object detection
Somesh Vyas
 
CIFAR-10
CIFAR-10CIFAR-10
CIFAR-10
satyam_madala
 
Object detection presentation
Object detection presentationObject detection presentation
Object detection presentation
AshwinBicholiya
 
Video object tracking with classification and recognition of objects
Video object tracking with classification and recognition of objectsVideo object tracking with classification and recognition of objects
Video object tracking with classification and recognition of objectsManish Khare
 
OpenCV
OpenCVOpenCV
Object Detection & Tracking
Object Detection & TrackingObject Detection & Tracking
Object Detection & Tracking
Akshay Gujarathi
 

What's hot (20)

Computer Vision image classification
Computer Vision image classificationComputer Vision image classification
Computer Vision image classification
 
Object Detection using Deep Neural Networks
Object Detection using Deep Neural NetworksObject Detection using Deep Neural Networks
Object Detection using Deep Neural Networks
 
Introduction to object detection
Introduction to object detectionIntroduction to object detection
Introduction to object detection
 
An Introduction to Computer Vision
An Introduction to Computer VisionAn Introduction to Computer Vision
An Introduction to Computer Vision
 
Image Processing and Computer Vision
Image Processing and Computer VisionImage Processing and Computer Vision
Image Processing and Computer Vision
 
Dip Image Segmentation
Dip Image SegmentationDip Image Segmentation
Dip Image Segmentation
 
CNN Tutorial
CNN TutorialCNN Tutorial
CNN Tutorial
 
Deep learning for object detection
Deep learning for object detectionDeep learning for object detection
Deep learning for object detection
 
Object detection
Object detectionObject detection
Object detection
 
Computer vision introduction
Computer vision  introduction Computer vision  introduction
Computer vision introduction
 
Application of edge detection
Application of edge detectionApplication of edge detection
Application of edge detection
 
[PR12] You Only Look Once (YOLO): Unified Real-Time Object Detection
[PR12] You Only Look Once (YOLO): Unified Real-Time Object Detection[PR12] You Only Look Once (YOLO): Unified Real-Time Object Detection
[PR12] You Only Look Once (YOLO): Unified Real-Time Object Detection
 
Introduction to Object recognition
Introduction to Object recognitionIntroduction to Object recognition
Introduction to Object recognition
 
Computer vision - images and image filtering
Computer vision - images and image filtering Computer vision - images and image filtering
Computer vision - images and image filtering
 
Object detection
Object detectionObject detection
Object detection
 
CIFAR-10
CIFAR-10CIFAR-10
CIFAR-10
 
Object detection presentation
Object detection presentationObject detection presentation
Object detection presentation
 
Video object tracking with classification and recognition of objects
Video object tracking with classification and recognition of objectsVideo object tracking with classification and recognition of objects
Video object tracking with classification and recognition of objects
 
OpenCV
OpenCVOpenCV
OpenCV
 
Object Detection & Tracking
Object Detection & TrackingObject Detection & Tracking
Object Detection & Tracking
 

Viewers also liked

Introduction to OpenCV with python (at taichung.py)
Introduction to OpenCV with python (at taichung.py)Introduction to OpenCV with python (at taichung.py)
Introduction to OpenCV with python (at taichung.py)
Max Lai
 
Robotics competition 2016
Robotics competition 2016Robotics competition 2016
Robotics competition 2016
Rohan Kotwani
 
Qr codes + ipads
Qr codes + ipadsQr codes + ipads
Qr codes + ipadstechiesue
 
Content curation
Content curationContent curation
Content curationtechiesue
 
An overview of mobile html + java script frameworks
An overview of mobile html + java script frameworksAn overview of mobile html + java script frameworks
An overview of mobile html + java script frameworksSasha dos Santos
 
Cell Phone Jammer , Intro
Cell Phone Jammer , IntroCell Phone Jammer , Intro
Cell Phone Jammer , Intro
Lakshman Basnet
 
Serious Games + Computer Science = Serious CS
Serious Games + Computer Science = Serious CSSerious Games + Computer Science = Serious CS
Serious Games + Computer Science = Serious CS
Katrin Becker
 
How to apply graphs to network management
How to apply graphs to network managementHow to apply graphs to network management
How to apply graphs to network management
Linkurious
 
12th CBSE Computer Science Project
12th CBSE Computer Science Project  12th CBSE Computer Science Project
12th CBSE Computer Science Project
Ashwin Francis
 
How to use phone calls and network analysis to identify criminals
How to use phone calls and network analysis to identify criminals How to use phone calls and network analysis to identify criminals
How to use phone calls and network analysis to identify criminals
Linkurious
 
Space Robotics
Space RoboticsSpace Robotics
Cellphone signal detector and jammer ppt
Cellphone signal detector and jammer pptCellphone signal detector and jammer ppt
Cellphone signal detector and jammer ppt
Amar Raj
 
Cyber security and attack analysis : how Cisco uses graph analytics
Cyber security and attack analysis : how Cisco uses graph analyticsCyber security and attack analysis : how Cisco uses graph analytics
Cyber security and attack analysis : how Cisco uses graph analytics
Linkurious
 
Face Recognition with OpenCV and scikit-learn
Face Recognition with OpenCV and scikit-learnFace Recognition with OpenCV and scikit-learn
Face Recognition with OpenCV and scikit-learn
Shiqiao Du
 
Network Security ,2014 and 2015 ieee projects list @ TMKS Infotech
Network Security ,2014 and 2015 ieee projects list @ TMKS InfotechNetwork Security ,2014 and 2015 ieee projects list @ TMKS Infotech
Network Security ,2014 and 2015 ieee projects list @ TMKS Infotech
Manju Nath
 
Using graph technologies to fight fraud
Using graph technologies to fight fraudUsing graph technologies to fight fraud
Using graph technologies to fight fraud
Linkurious
 
Face Recognition using OpenCV
Face Recognition using OpenCVFace Recognition using OpenCV
Face Recognition using OpenCV
Vasile Chelban
 
Building Mobile Apps with Cordova , AngularJS and Ionic
Building Mobile Apps with Cordova , AngularJS and IonicBuilding Mobile Apps with Cordova , AngularJS and Ionic
Building Mobile Apps with Cordova , AngularJS and Ionic
Kadhem Soltani
 
Face recognition technology - BEST PPT
Face recognition technology - BEST PPTFace recognition technology - BEST PPT
Face recognition technology - BEST PPTSiddharth Modi
 
12th CBSE Computer Science Project
12th CBSE Computer Science Project12th CBSE Computer Science Project
12th CBSE Computer Science Project
Ashwin Francis
 

Viewers also liked (20)

Introduction to OpenCV with python (at taichung.py)
Introduction to OpenCV with python (at taichung.py)Introduction to OpenCV with python (at taichung.py)
Introduction to OpenCV with python (at taichung.py)
 
Robotics competition 2016
Robotics competition 2016Robotics competition 2016
Robotics competition 2016
 
Qr codes + ipads
Qr codes + ipadsQr codes + ipads
Qr codes + ipads
 
Content curation
Content curationContent curation
Content curation
 
An overview of mobile html + java script frameworks
An overview of mobile html + java script frameworksAn overview of mobile html + java script frameworks
An overview of mobile html + java script frameworks
 
Cell Phone Jammer , Intro
Cell Phone Jammer , IntroCell Phone Jammer , Intro
Cell Phone Jammer , Intro
 
Serious Games + Computer Science = Serious CS
Serious Games + Computer Science = Serious CSSerious Games + Computer Science = Serious CS
Serious Games + Computer Science = Serious CS
 
How to apply graphs to network management
How to apply graphs to network managementHow to apply graphs to network management
How to apply graphs to network management
 
12th CBSE Computer Science Project
12th CBSE Computer Science Project  12th CBSE Computer Science Project
12th CBSE Computer Science Project
 
How to use phone calls and network analysis to identify criminals
How to use phone calls and network analysis to identify criminals How to use phone calls and network analysis to identify criminals
How to use phone calls and network analysis to identify criminals
 
Space Robotics
Space RoboticsSpace Robotics
Space Robotics
 
Cellphone signal detector and jammer ppt
Cellphone signal detector and jammer pptCellphone signal detector and jammer ppt
Cellphone signal detector and jammer ppt
 
Cyber security and attack analysis : how Cisco uses graph analytics
Cyber security and attack analysis : how Cisco uses graph analyticsCyber security and attack analysis : how Cisco uses graph analytics
Cyber security and attack analysis : how Cisco uses graph analytics
 
Face Recognition with OpenCV and scikit-learn
Face Recognition with OpenCV and scikit-learnFace Recognition with OpenCV and scikit-learn
Face Recognition with OpenCV and scikit-learn
 
Network Security ,2014 and 2015 ieee projects list @ TMKS Infotech
Network Security ,2014 and 2015 ieee projects list @ TMKS InfotechNetwork Security ,2014 and 2015 ieee projects list @ TMKS Infotech
Network Security ,2014 and 2015 ieee projects list @ TMKS Infotech
 
Using graph technologies to fight fraud
Using graph technologies to fight fraudUsing graph technologies to fight fraud
Using graph technologies to fight fraud
 
Face Recognition using OpenCV
Face Recognition using OpenCVFace Recognition using OpenCV
Face Recognition using OpenCV
 
Building Mobile Apps with Cordova , AngularJS and Ionic
Building Mobile Apps with Cordova , AngularJS and IonicBuilding Mobile Apps with Cordova , AngularJS and Ionic
Building Mobile Apps with Cordova , AngularJS and Ionic
 
Face recognition technology - BEST PPT
Face recognition technology - BEST PPTFace recognition technology - BEST PPT
Face recognition technology - BEST PPT
 
12th CBSE Computer Science Project
12th CBSE Computer Science Project12th CBSE Computer Science Project
12th CBSE Computer Science Project
 

Similar to Introduction to OpenCV

03 image transformations_i
03 image transformations_i03 image transformations_i
03 image transformations_i
ankit_ppt
 
Log polar coordinates
Log polar coordinatesLog polar coordinates
Log polar coordinates
Oğul Göçmen
 
Generating super resolution images using transformers
Generating super resolution images using transformersGenerating super resolution images using transformers
Generating super resolution images using transformers
NEERAJ BAGHEL
 
FAST AND EFFICIENT IMAGE COMPRESSION BASED ON PARALLEL COMPUTING USING MATLAB
FAST AND EFFICIENT IMAGE COMPRESSION BASED ON PARALLEL COMPUTING USING MATLABFAST AND EFFICIENT IMAGE COMPRESSION BASED ON PARALLEL COMPUTING USING MATLAB
FAST AND EFFICIENT IMAGE COMPRESSION BASED ON PARALLEL COMPUTING USING MATLAB
Journal For Research
 
Lect 03 - first portion
Lect 03 - first portionLect 03 - first portion
Lect 03 - first portion
Moe Moe Myint
 
AIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdfAIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdf
ssuserb4d806
 
CPSC 40406040Computer Graphics ImagesAssigned Sept 21,.docx
CPSC 40406040Computer Graphics ImagesAssigned Sept 21,.docxCPSC 40406040Computer Graphics ImagesAssigned Sept 21,.docx
CPSC 40406040Computer Graphics ImagesAssigned Sept 21,.docx
richardnorman90310
 
1 of 6 LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
1 of 6  LAB 5 IMAGE FILTERING ECE180 Introduction to.docx1 of 6  LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
1 of 6 LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
mercysuttle
 
LAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSING
LAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSINGLAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSING
LAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSING
Priyanka Rathore
 
Writeup advanced lane_lines_project
Writeup advanced lane_lines_projectWriteup advanced lane_lines_project
Writeup advanced lane_lines_project
Manish Jauhari
 
CS 354 Pixel Updating
CS 354 Pixel UpdatingCS 354 Pixel Updating
CS 354 Pixel Updating
Mark Kilgard
 
Estrazione automatica delle linee in un'immagine digitale
Estrazione automatica delle linee in un'immagine digitaleEstrazione automatica delle linee in un'immagine digitale
Estrazione automatica delle linee in un'immagine digitale
francescapadoin
 
Image processing with matlab
Image processing with matlabImage processing with matlab
Image processing with matlab
Aman Gupta
 
Intro_OpenCV.ppt
Intro_OpenCV.pptIntro_OpenCV.ppt
Intro_OpenCV.ppt
RithikRaj25
 
Matlab 3
Matlab 3Matlab 3
Matlab 3asguna
 
XIX PUG-PE - Pygame game development
XIX PUG-PE - Pygame game developmentXIX PUG-PE - Pygame game development
XIX PUG-PE - Pygame game development
matheuscmpm
 
B Eng Final Year Project Presentation
B Eng Final Year Project PresentationB Eng Final Year Project Presentation
B Eng Final Year Project Presentation
jesujoseph
 
Image Classification using Deep Learning
Image Classification using Deep LearningImage Classification using Deep Learning
Image Classification using Deep Learning
IRJET Journal
 
Image processing
Image processingImage processing
Image processingmaheshpene
 

Similar to Introduction to OpenCV (20)

03 image transformations_i
03 image transformations_i03 image transformations_i
03 image transformations_i
 
Log polar coordinates
Log polar coordinatesLog polar coordinates
Log polar coordinates
 
Report
ReportReport
Report
 
Generating super resolution images using transformers
Generating super resolution images using transformersGenerating super resolution images using transformers
Generating super resolution images using transformers
 
FAST AND EFFICIENT IMAGE COMPRESSION BASED ON PARALLEL COMPUTING USING MATLAB
FAST AND EFFICIENT IMAGE COMPRESSION BASED ON PARALLEL COMPUTING USING MATLABFAST AND EFFICIENT IMAGE COMPRESSION BASED ON PARALLEL COMPUTING USING MATLAB
FAST AND EFFICIENT IMAGE COMPRESSION BASED ON PARALLEL COMPUTING USING MATLAB
 
Lect 03 - first portion
Lect 03 - first portionLect 03 - first portion
Lect 03 - first portion
 
AIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdfAIML4 CNN lab256 1hr (111-1).pdf
AIML4 CNN lab256 1hr (111-1).pdf
 
CPSC 40406040Computer Graphics ImagesAssigned Sept 21,.docx
CPSC 40406040Computer Graphics ImagesAssigned Sept 21,.docxCPSC 40406040Computer Graphics ImagesAssigned Sept 21,.docx
CPSC 40406040Computer Graphics ImagesAssigned Sept 21,.docx
 
1 of 6 LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
1 of 6  LAB 5 IMAGE FILTERING ECE180 Introduction to.docx1 of 6  LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
1 of 6 LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
 
LAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSING
LAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSINGLAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSING
LAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSING
 
Writeup advanced lane_lines_project
Writeup advanced lane_lines_projectWriteup advanced lane_lines_project
Writeup advanced lane_lines_project
 
CS 354 Pixel Updating
CS 354 Pixel UpdatingCS 354 Pixel Updating
CS 354 Pixel Updating
 
Estrazione automatica delle linee in un'immagine digitale
Estrazione automatica delle linee in un'immagine digitaleEstrazione automatica delle linee in un'immagine digitale
Estrazione automatica delle linee in un'immagine digitale
 
Image processing with matlab
Image processing with matlabImage processing with matlab
Image processing with matlab
 
Intro_OpenCV.ppt
Intro_OpenCV.pptIntro_OpenCV.ppt
Intro_OpenCV.ppt
 
Matlab 3
Matlab 3Matlab 3
Matlab 3
 
XIX PUG-PE - Pygame game development
XIX PUG-PE - Pygame game developmentXIX PUG-PE - Pygame game development
XIX PUG-PE - Pygame game development
 
B Eng Final Year Project Presentation
B Eng Final Year Project PresentationB Eng Final Year Project Presentation
B Eng Final Year Project Presentation
 
Image Classification using Deep Learning
Image Classification using Deep LearningImage Classification using Deep Learning
Image Classification using Deep Learning
 
Image processing
Image processingImage processing
Image processing
 

Introduction to OpenCV

  • 1. INTRODUCTION TO OPENCV HANDS-ON WORKSHOP IN PYTHON Amit Mandelbaum TIP 2016, Jerusalem mangate@gmail.com
  • 2. OVERVIEW  OpenCV is the most popular Image Processing and Computer Vision library  Free for both academic and commercial use  Very easy to learn  It has C++, C, Python and Java interfaces and supports Windows, Linux, Mac OS, iOS and Android  Designed for computational efficiency and with a strong focus on real-time applications  Lot of documentation online
  • 3. RESOURCES  Official site: http://opencv.org/  Tutorials  http://docs.opencv.org/3.0- beta/doc/py_tutorials/py_tutorials.html (official, python)  http://docs.opencv.org/2.4/doc/tutorials/tutorials.html (official c++)  https://opencv-python-tutroals.readthedocs.io/en/latest/ (python)  http://opencvexamples.blogspot.com/ (c++)  http://www.pyimagesearch.com/ (some cool free advanced tutorials)  Google
  • 4. WORKSHOP OUTLINE (TOPICS)  Loading, showing and saving images  Histograms and Histograms equalizations  Gamma correction  Smoothing, sharpening and noise removal  Morphological operations (erosion, dilation)  Edge detection  Transformation  Adaptive thresholding  And finally: Document scanner
  • 5. LOADING, SHOWING AND SAVING IMAGES  Loading: image = cv2.imread(“file_name",0) (0 means Gray Scale, no number will use original image’s colors)  Displaying: cv2.imshow(“some headline",image) (Usually followed by: cv2.waitKey(0) so the image will not close immediately)  Saving: cv2.imwrite(“file_name",image)  Code: load_and_display.py
  • 6. HISTOGRAMS AND HISTOGRAMS EQUALIZATIONS  Histogram: Showing how many pixels have a certain intensity (between 0 and 255) in a picture.
  • 7. HISTOGRAMS AND HISTOGRAMS EQUALIZATIONS (CONT.)  “Good” pictures have their histograms nearly equally spread over the entire range.  However in a lot of pictures this is not always the case
  • 8. HISTOGRAMS AND HISTOGRAMS EQUALIZATIONS (CONT.)  Solution: Histogram equalization (see theoretical equations here: http://www.math.uci.edu/icamp/courses/math77c/demos/hist_eq.pdf)  With openCV: image2 = cv2.equalizeHist(image) Code: load_and_display.py
  • 9. HISTOGRAMS AND HISTOGRAMS EQUALIZATIONS (CONT.)  On color images:  Split the color channels with: b,g,r = cv2.split(image)  Equalize each channel separately  Merge the channels with: image2 = cv2.merge((b,g,r))  Code: equalizing_color_images.py
  • 10. GAMMA CORRECTION  Sometimes images are too dark, or too bright  Fixing it with just adding/substracting intensities produses bad results  Solution: Gamma correction  Transform intensities from [0,255] to [0,1] with a LUT (look up table)  Apply this to all pixels: O = I ^ (1 / G) (G is the gamma value, higher = brighter)  Transform back to [0,255] with LUT
  • 11. GAMMA CORRECTION (CONT.)  In openCV: def adjust_gamma(image, gamma=1.0): invGamma = 1.0 / gamma table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype("uint8") return cv2.LUT(image, table) adjusted = adjust_gamma(original, gamma=2) Code: gamma_correction.py
  • 12. SMOOTHING, SHARPENING AND NOISE REMOVAL  Smoothing is done by applying a simple filter to the picture, for example (3x3 kernel): Each pixel is averaged with its 8 neighbors.  Gaussian smoothing : Each pixel is averaged (with Gaussian weights) with its 8 neighbors.  Median smoothing: Each pixel is gets the median value of him and its 8 neighbors.
  • 13. SMOOTHING, SHARPENING AND NOISE REMOVAL (CONT.)  In openCV (5x5 kernel:  average_blur = cv2.blur(image,(5,5))  gaussian = cv2.GaussianBlur(image,(5,5),0)  median = cv2.medianBlur(image,5) Code: smoothing _and_cleaning.py
  • 14. SMOOTHING, SHARPENING AND NOISE REMOVAL (CONT.)  Sharpening: Done be subtracting from the picture, a Gaussian blurred version of itself  In openCV: gaussian = cv2.GaussianBlur(image,(9,9),10) sharpened = cv2.addWeighted(image,1.5,gassuian,-0.5,0) Code: smoothing _and_cleaning.py
  • 15. SMOOTHING, SHARPENING AND NOISE REMOVAL (CONT.)  Some types of noise (especially Salt & Pepper) can be removed by using a median filter (with a small kernel) Code: smoothing _and_cleaning.py
  • 16. MORPHOLOGICAL OPERATIONS (EROSION, DILATION)  Morphological transformations are some simple operations based on the image shape.  It is normally performed on binary images.  It needs two inputs, one is our original image, second one is called structuring element or kernel which decides the nature of operation.  Two basic morphological operators are Erosion and Dilation  Erosion: Match the value of all pixels in the kernel to the one with the minimum value .  Dilation: Match the value of all pixels in the kernel to the one with the maximum value .
  • 17. MORPHOLOGICAL OPERATIONS (EROSION, DILATION) (CONT.)  On openCV (with kernel of 5x5): kernel = np.ones((5,5),np.uint8) eroded = cv2.erode(image,kernel) dilated = cv2.dilate(image,kernel) Original Eroded Dilated Code: erosion_dialation_inversion.py
  • 18. EDGE DETECTION (CANNY)  Canny Edge Detection is a popular edge detection algorithm. It was developed by John F. Canny in 1986  Does the following steps:  Cleaning the image by blurring it.  Finding Intensity Gradient of the Image: Using Sobel to find intensities of gradients in x and y directions creates a picture of gradient intensities.  Non-maximum Suppression: Suppress (set to 0) all pixels which are not a local maximum, to thin the edges.  Hysteresis Thresholding: Any edges with intensity gradient more than maxVal are sure to be edges and those below minVal are sure to be non-edges, so discarded. Those who lie between these two thresholds are classified edges or non-edges based on their connectivity. If they are connected to “sure-edge” pixels, they are considered to be part of edges. Otherwise, they are also discarded
  • 19. EDGE DETECTION (CANNY) (CONT.)  In openCV: edges = cv2.Canny(img,100,200) (The two numbers are min-val and max-val) Code: edge_detection.py
  • 20. TRANSFORMATION  Transformation: Reshape the picture such that is gets 4 co-ordinates from the original picture and 4 new coordinates, and trasnforms the picture so the 4 points (and all points between them) will match the new ones.  In openCV : M = cv2.getPerspectiveTransform(pts1,pts2) dst = cv2.warpPerspective(img,M,(257,259)) (The last two numbers are the size of the new image) Code: trasnformation_and_adaptive_threshold.py
  • 21. ADAPTIVE THRESHOLDING  Thresholding: Set pixel to 255 if it’s intensity is above a certain threshold, otherwise set to 0.  Simple thresholding: Threshold is constant for the entire picture.  Adaptive thresholding: Different thresholds for different regions of the same image  Mean: Threshold value is the mean of neighborhood area.  Gaussian: Threshold value is the weighted sum of neighborhood values where weights are a Gaussian window.
  • 22. ADAPTIVE THRESHOLDING (CONT.)  In openCV: ret,th1 = cv2.threshold(dst,127,255,cv2.THRESH_BINARY) th2 = cv2.adaptiveThreshold(dst,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2) th3 = cv2.adaptiveThreshold(dst,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) Code: trasnformation_and_adaptiv e_threshold.py
  • 23. DOCUMENT SCANNER  Steps:  Edge detection  Contour (find borders  Transformation (So only document remains)  Adaptive thresholding  Code: scan.py
  • 24. DOCUMENT SCANNER (CONT.) Original Edge detection Contour Transformation and Thresholding