SlideShare una empresa de Scribd logo
1 de 25
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!

Más contenido relacionado

La actualidad más candente

Computer vision introduction
Computer vision  introduction Computer vision  introduction
Computer vision introduction Wael Badawy
 
Automated Face Detection System
Automated Face Detection SystemAutomated Face Detection System
Automated Face Detection SystemAbhiroop Ghatak
 
Application of-image-segmentation-in-brain-tumor-detection
Application of-image-segmentation-in-brain-tumor-detectionApplication of-image-segmentation-in-brain-tumor-detection
Application of-image-segmentation-in-brain-tumor-detectionMyat Myint Zu Thin
 
Introduction to object detection
Introduction to object detectionIntroduction to object detection
Introduction to object detectionBrodmann17
 
Yurii Pashchenko: Zero-shot learning capabilities of CLIP model from OpenAI
Yurii Pashchenko: Zero-shot learning capabilities of CLIP model from OpenAIYurii Pashchenko: Zero-shot learning capabilities of CLIP model from OpenAI
Yurii Pashchenko: Zero-shot learning capabilities of CLIP model from OpenAILviv Startup Club
 
Real Time Object Tracking
Real Time Object TrackingReal Time Object Tracking
Real Time Object TrackingVanya Valindria
 
Latent diffusions vs DALL-E v2
Latent diffusions vs DALL-E v2Latent diffusions vs DALL-E v2
Latent diffusions vs DALL-E v2Vitaly Bondar
 
Object detection
Object detectionObject detection
Object detectionSomesh Vyas
 
Image processing on matlab presentation
Image processing on matlab presentationImage processing on matlab presentation
Image processing on matlab presentationNaatchammai Ramanathan
 
Object Detection & Tracking
Object Detection & TrackingObject Detection & Tracking
Object Detection & TrackingAkshay Gujarathi
 
ppt 20BET1024.pptx
ppt 20BET1024.pptxppt 20BET1024.pptx
ppt 20BET1024.pptxManeetBali
 
Object detection with deep learning
Object detection with deep learningObject detection with deep learning
Object detection with deep learningSushant Shrivastava
 
Deep learning based object detection basics
Deep learning based object detection basicsDeep learning based object detection basics
Deep learning based object detection basicsBrodmann17
 
Multiple object detection
Multiple object detectionMultiple object detection
Multiple object detectionSAURABH KUMAR
 

La actualidad más candente (20)

Computer Vision Introduction
Computer Vision IntroductionComputer Vision Introduction
Computer Vision Introduction
 
OpenCV
OpenCVOpenCV
OpenCV
 
Computer vision introduction
Computer vision  introduction Computer vision  introduction
Computer vision introduction
 
Automated Face Detection System
Automated Face Detection SystemAutomated Face Detection System
Automated Face Detection System
 
Application of-image-segmentation-in-brain-tumor-detection
Application of-image-segmentation-in-brain-tumor-detectionApplication of-image-segmentation-in-brain-tumor-detection
Application of-image-segmentation-in-brain-tumor-detection
 
Image captioning
Image captioningImage captioning
Image captioning
 
Introduction to object detection
Introduction to object detectionIntroduction to object detection
Introduction to object detection
 
Yurii Pashchenko: Zero-shot learning capabilities of CLIP model from OpenAI
Yurii Pashchenko: Zero-shot learning capabilities of CLIP model from OpenAIYurii Pashchenko: Zero-shot learning capabilities of CLIP model from OpenAI
Yurii Pashchenko: Zero-shot learning capabilities of CLIP model from OpenAI
 
Real Time Object Tracking
Real Time Object TrackingReal Time Object Tracking
Real Time Object Tracking
 
Human Emotion Recognition
Human Emotion RecognitionHuman Emotion Recognition
Human Emotion Recognition
 
Latent diffusions vs DALL-E v2
Latent diffusions vs DALL-E v2Latent diffusions vs DALL-E v2
Latent diffusions vs DALL-E v2
 
Object detection
Object detectionObject detection
Object detection
 
Image processing on matlab presentation
Image processing on matlab presentationImage processing on matlab presentation
Image processing on matlab presentation
 
Object Detection & Tracking
Object Detection & TrackingObject Detection & Tracking
Object Detection & Tracking
 
ppt 20BET1024.pptx
ppt 20BET1024.pptxppt 20BET1024.pptx
ppt 20BET1024.pptx
 
Object detection with deep learning
Object detection with deep learningObject detection with deep learning
Object detection with deep learning
 
Object detection
Object detectionObject detection
Object detection
 
Deep learning based object detection basics
Deep learning based object detection basicsDeep learning based object detection basics
Deep learning based object detection basics
 
Multiple object detection
Multiple object detectionMultiple object detection
Multiple object detection
 
Computer Vision.pptx
Computer Vision.pptxComputer Vision.pptx
Computer Vision.pptx
 

Destacado

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 2016Rohan 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 , IntroLakshman Basnet
 
Serious Games + Computer Science = Serious CS
Serious Games + Computer Science = Serious CSSerious Games + Computer Science = Serious CS
Serious Games + Computer Science = Serious CSKatrin 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 managementLinkurious
 
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
 
Cellphone signal detector and jammer ppt
Cellphone signal detector and jammer pptCellphone signal detector and jammer ppt
Cellphone signal detector and jammer pptAmar 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 analyticsLinkurious
 
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-learnShiqiao 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 InfotechManju Nath
 
Using graph technologies to fight fraud
Using graph technologies to fight fraudUsing graph technologies to fight fraud
Using graph technologies to fight fraudLinkurious
 
Face Recognition using OpenCV
Face Recognition using OpenCVFace Recognition using OpenCV
Face Recognition using OpenCVVasile 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 IonicKadhem 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 ProjectAshwin Francis
 

Destacado (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 a Introduction to OpenCV

03 image transformations_i
03 image transformations_i03 image transformations_i
03 image transformations_iankit_ppt
 
Generating super resolution images using transformers
Generating super resolution images using transformersGenerating super resolution images using transformers
Generating super resolution images using transformersNEERAJ 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 MATLABJournal For Research
 
Lect 03 - first portion
Lect 03 - first portionLect 03 - first portion
Lect 03 - first portionMoe 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).pdfssuserb4d806
 
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,.docxrichardnorman90310
 
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.docxmercysuttle
 
LAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSING
LAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSINGLAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSING
LAPLACE TRANSFORM SUITABILITY FOR IMAGE PROCESSINGPriyanka Rathore
 
Writeup advanced lane_lines_project
Writeup advanced lane_lines_projectWriteup advanced lane_lines_project
Writeup advanced lane_lines_projectManish Jauhari
 
CS 354 Pixel Updating
CS 354 Pixel UpdatingCS 354 Pixel Updating
CS 354 Pixel UpdatingMark 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 digitalefrancescapadoin
 
Image processing with matlab
Image processing with matlabImage processing with matlab
Image processing with matlabAman Gupta
 
Intro_OpenCV.ppt
Intro_OpenCV.pptIntro_OpenCV.ppt
Intro_OpenCV.pptRithikRaj25
 
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 developmentmatheuscmpm
 
B Eng Final Year Project Presentation
B Eng Final Year Project PresentationB Eng Final Year Project Presentation
B Eng Final Year Project Presentationjesujoseph
 
Image Classification using Deep Learning
Image Classification using Deep LearningImage Classification using Deep Learning
Image Classification using Deep LearningIRJET Journal
 
Image processing
Image processingImage processing
Image processingmaheshpene
 

Similar a 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