Buy Ebook Building Computer Vision Applications Using Artificial Neural Networks, 2nd Edition Shamshad Ansari Cheap Price
Buy Ebook Building Computer Vision Applications Using Artificial Neural Networks, 2nd Edition Shamshad Ansari Cheap Price
com
https://ebookmass.com/product/building-computer-vision-
applications-using-artificial-neural-networks-2nd-edition-
shamshad-ansari/
OR CLICK HERE
DOWLOAD NOW
https://ebookmass.com/product/analysis-and-visualization-of-discrete-
data-using-neural-networks-koji-koyamada/
ebookmass.com
https://ebookmass.com/product/3-d-computer-vision-principles-
algorithms-and-applications-1st-edition-yu-jin-zhang/
ebookmass.com
https://ebookmass.com/product/accelerators-for-convolutional-neural-
networks-arslan-munir/
ebookmass.com
https://ebookmass.com/product/exercise-physiology-theory-and-
application-to-fitness-and-performance-eleventh-edition-scott-k-
powers/
ebookmass.com
The Realizations of the Self 1st ed. Edition Andrea
Altobrando
https://ebookmass.com/product/the-realizations-of-the-self-1st-ed-
edition-andrea-altobrando/
ebookmass.com
https://ebookmass.com/product/iron-flame-fourth-wing-empyrian-
books-1-and-2-2nd-edition-rebecca-yarros/
ebookmass.com
https://ebookmass.com/product/business-and-society-ethics-
sustainability-and-stakeholder-management-9th-edition-ebook-pdf/
ebookmass.com
https://ebookmass.com/product/current-diagnosis-and-treatment-
surgery-14-e-14th-edition-ebook-pdf/
ebookmass.com
Make Virtual Learning Matter: How to Turn Virtual
Classrooms into a Remarkable, Authentic Experience for
Kids Paul Axtell
https://ebookmass.com/product/make-virtual-learning-matter-how-to-
turn-virtual-classrooms-into-a-remarkable-authentic-experience-for-
kids-paul-axtell/
ebookmass.com
Building Computer Vision
Applications Using
Artificial Neural Networks
With Examples in OpenCV
and TensorFlow with Python
Second Edition
Shamshad Ansari
Building Computer Vision Applications Using Artificial Neural Networks: With
Examples in OpenCV and TensorFlow with Python, Second Edition
Shamshad Ansari
Centreville, VA, USA
Acknowledgments��������������������������������������������������������������������������������������������������xix
Introduction������������������������������������������������������������������������������������������������������������xxi
v
Table of Contents
Additional Libraries��������������������������������������������������������������������������������������������������������������������� 12
Installing SciPy���������������������������������������������������������������������������������������������������������������������� 12
Installing Matplotlib��������������������������������������������������������������������������������������������������������������� 12
Summary������������������������������������������������������������������������������������������������������������������������������� 12
vi
Table of Contents
vii
Table of Contents
GLCM����������������������������������������������������������������������������������������������������������������������������������� 140
HOGs������������������������������������������������������������������������������������������������������������������������������������ 145
LBP�������������������������������������������������������������������������������������������������������������������������������������� 152
Feature Selection���������������������������������������������������������������������������������������������������������������������� 159
Filter Method����������������������������������������������������������������������������������������������������������������������� 160
Wrapper Method������������������������������������������������������������������������������������������������������������������ 160
Embedded Method�������������������������������������������������������������������������������������������������������������� 161
Model Training��������������������������������������������������������������������������������������������������������������������������� 162
How to Do Machine Learning���������������������������������������������������������������������������������������������� 162
Supervised Learning������������������������������������������������������������������������������������������������������������ 163
Unsupervised Learning�������������������������������������������������������������������������������������������������������� 164
Model Deployment�������������������������������������������������������������������������������������������������������������������� 165
Summary���������������������������������������������������������������������������������������������������������������������������������� 167
viii
Table of Contents
Our First Computer Vision Model with Deep Learning: Classification of Handwritten Digits���� 207
Model Overview������������������������������������������������������������������������������������������������������������������������������������������������ 207
Model Implementation��������������������������������������������������������������������������������������������������������� 208
Model Evaluation����������������������������������������������������������������������������������������������������������������������� 217
Overfitting���������������������������������������������������������������������������������������������������������������������������� 217
Underfitting�������������������������������������������������������������������������������������������������������������������������� 219
Hyperparameters���������������������������������������������������������������������������������������������������������������������� 223
TensorBoard������������������������������������������������������������������������������������������������������������������������ 224
Experiments for Hyperparameter Tuning����������������������������������������������������������������������������� 225
Saving and Restoring Model����������������������������������������������������������������������������������������������������� 229
Save Model Checkpoints During Training���������������������������������������������������������������������������� 230
Manually Save Weights������������������������������������������������������������������������������������������������������� 233
Load the Saved Weights and Retrain the Model������������������������������������������������������������������ 233
Saving the Entire Model������������������������������������������������������������������������������������������������������ 234
Retraining the Existing Model���������������������������������������������������������������������������������������������� 234
Using a Trained Model in Applications��������������������������������������������������������������������������������� 235
Convolutional Neural Network�������������������������������������������������������������������������������������������������� 236
Architecture of CNN������������������������������������������������������������������������������������������������������������� 236
How a CNN Works���������������������������������������������������������������������������������������������������������������� 238
Summary of CNN Concepts������������������������������������������������������������������������������������������������� 243
Training a CNN Model: Pneumonia Detection from Chest X-rays���������������������������������������� 244
Examples of Popular CNNs�������������������������������������������������������������������������������������������������� 255
Summary����������������������������������������������������������������������������������������������������������������������������� 260
ix
Table of Contents
x
Table of Contents
xi
Table of Contents
Dataset�������������������������������������������������������������������������������������������������������������������������������� 410
Downloading VGGFace2 Data���������������������������������������������������������������������������������������������� 412
Data Preparation������������������������������������������������������������������������������������������������������������������ 414
Model Training��������������������������������������������������������������������������������������������������������������������� 419
Evaluation���������������������������������������������������������������������������������������������������������������������������� 420
Developing a Real-Time Face Recognition System������������������������������������������������������������������� 421
Face Detection Model���������������������������������������������������������������������������������������������������������� 421
Classifier for Face Recognition�������������������������������������������������������������������������������������������� 422
Summary���������������������������������������������������������������������������������������������������������������������������������� 428
xii
Table of Contents
Index��������������������������������������������������������������������������������������������������������������������� 513
xiii
About the Author
Shamshad Ansari is an author, inventor, and thought
leader in the fields of computer vision, machine learning,
artificial intelligence, and cognitive science. He has
extensive experience in high-scale, distributed, and parallel
computing. Sam currently serves as an adjunct professor at
George Mason University, teaching graduate-level programs
within the Data Analytics Engineering department of the
Volgenau School of Engineering. His areas of instruction
encompass machine learning, natural language processing,
and computer vision, where he imparts his knowledge and
expertise to aspiring professionals.
Having authored multiple publications on topics such as machine learning, RFID,
and high-scale enterprise computing, Sam’s contributions extend beyond academia. He
holds four US patents related to healthcare AI, showcasing his innovative mindset and
practical application of technology.
Throughout his extensive 20+ years of experience in enterprise software
development, Sam has been involved with several tech startups and early-stage
companies. He has played pivotal roles in building and expanding tech teams from
the ground up, contributing to their eventual acquisition by larger organizations.
At the beginning of his career, he worked with esteemed institutions such as the US
Department of Defense (DOD) and IBM, honing his skills and knowledge in the
industry.
Currently, Sam serves as the president and CEO of Accure, Inc., an AI company
that he founded. He is the creator and architect of, and continues to make significant
contributions to, Momentum AI, a no-code platform that encompasses data
engineering, machine learning, AI, MLOps, data warehousing, and business intelligence.
Throughout his career, Sam has made notable contributions in various domains
including healthcare, retail, supply chain, banking and finance, and manufacturing.
xv
About the Author
xvi
About the Technical Reviewers
Bharath Kumar Bolla has over 12 years of experience
and is a senior data scientist at Salesforce, Hyderabad.
Bharath obtained a master’s degree in data science from
the University of Arizona and a master’s degree in life
sciences from Mississippi State University. Bharath worked
as a research scientist for seven years at the University of
Georgia, Emory University, and Eurofins LLC. At Verizon,
Bharath led a team to build a “Smart Pricing” solution, and
at Happiest Minds, he worked on AI-based digital marketing
products. Along with his day-to-day responsibilities, Bharath is a mentor and an active
researcher with more than 20 publications in conferences and journals. Bharath received
the “40 Under 40 Data Scientists 2021” award from Analytics India Magazine for his
accomplishments.
xvii
Acknowledgments
I wrote this book with two primary objectives in mind. First, I aimed to comprehensively
construct the foundations of computer vision concepts, starting from the basics and
progressing to an advanced level. Secondly, I aspired to furnish a practical guide for
the application of these concepts in real-world computer vision systems by including
practical use cases and code examples.
Achieving these objectives required meticulous organization of topics, integration
of content with meaningful and practical use cases, and thorough testing of the code,
all of which demanded my undivided attention throughout the writing process. This
accomplishment wouldn’t have been possible without the unwavering support of my
family. My gratitude is immeasurable towards my wife, Shazia, who managed the care of
our two daughters (Erum and Dua), ensuring they remained engaged while I dedicated
myself to the writing of this book. She ingeniously transformed this experience into a
positive experience for both them and myself. Remarkably, my children began tracking
my progress, celebrating each completion of a section, subsection, or chapter. Their
enthusiasm became a wellspring of energy and motivation that significantly enriched my
writing experience. I still do not know what magic my wife used to do this.
My life is indebted to Anumati Bhagi and Ashok Bhagi, who are no less than parents
to me; their love and support always motivate me.
This book is a collection of my lifetime experiences that I gained by working with
some of the greatest engineers, data scientists, and business professionals. I would
like to thank all my colleagues at Accure and all the past companies I have worked at. I
sincerely thank all my teachers, professors, and mentors who enlightened me with their
knowledge and wisdom.
Working with the Apress editorial team, which includes remarkable individuals like
Mark Powers and Laura Berendson, has been an incredible experience. I want to extend
a special thank you to Shonmirin PA, the project coordinator, who has been instrumental
in coordinating with the editorial team and technical reviewers and providing prompt
and helpful responses to my questions along the way.
xix
Acknowledgments
xx
Introduction
For over 20 years, I have had the privilege of working with distinguished data scientists
and computer vision experts, some of the finest in their field. Throughout this journey,
I’ve gained invaluable insights, particularly in the realm of building scalable computer
vision systems following the best practices. This book encapsulates the wisdom acquired
from my work experience, as well as the collective knowledge amassed from the
exceptional individuals with whom I’ve had the fortune to work or collaborate. This book
also presents knowledge I’ve gained from the works of some of the greatest contributors
and thought leaders of computer vision. I have provided references to their work at
appropriate places throughout the book.
When I hire new engineers and scientists, one of my main challenges has been giving
them effective training so that they can quickly start contributing to the development
of computer vision systems. With numerous online resources and books available on
various computer vision topics, it’s easy to feel overwhelmed by the sheer amount of
information. This is especially true since the field of computer vision is extensive and
intricate.
In this book, my aim is to offer a structured and methodical approach to learning
computer visions systems. You will learn essential concepts first and then build on
those concepts by working through practical code examples that pertain to real-world
computer vision systems. This approach will help you connect the dots as you progress
through the chapters. I’ve structured this book to be as hands-on and practical as
possible to assist you effectively.
This book begins by explaining the core concepts of computer vision. It presents
code examples to help you understand these ideas better. In the beginning, the examples
mainly use OpenCV with the Python language.
This book also covers the basic concepts of machine learning and then gradually
moves into more complex concepts like artificial neural networks and deep learning.
Every concept is reinforced with one or more practical code examples that show how
the concept is applied in practice. Machine learning–related concepts are illustrated via
code examples in TensorFlow with Python.
xxi
Introduction
This book presents 11 examples, including working code, that demonstrate how
computer vision is used in real life. These examples are from different domains like
healthcare, surveillance, security, and manufacturing. To help you understand the code,
I explain each line step by step.
Chapters 7, 8, and 9 are dedicated to building practical computer vision–based
systems. These chapters show you all stages of how to create vision systems, from
obtaining pictures or videos, to building a data pipeline, to training a model, and finally
deploying the model for real situations.
Training state-of-the-art computer vision models requires a lot of hardware
resources. It is desirable and economically beneficial to train computer vision models on
a cloud infrastructure to leverage the latest hardware resources, such as GPUs, and pay-
as-you-go cost models. The final chapter, Chapter 10, provides step-by-step instructions
for building machine learning–based computer vision applications on three popular
cloud infrastructures: Google Cloud Platform, Amazon AWS, and Microsoft Azure.
Even though this book starts from explaining a single pixel of an image and goes up
to teaching how to use cloud computers for neural networks training, there are certain
prerequisites to better understand the concepts presented in this book. You should
already know how to use the Python programming language.
The purpose of this book is to assist working professionals, programmers, data
scientists, and even students (undergraduate and graduate) acquire hands-on skills for
building computer vision applications using artificial neural networks.
xxii
CHAPTER 1
Prerequisites and
Software Installation
This book is a practical guide that explores the process of building computer vision
applications using the Python programming language. Throughout this book, you will
gain a comprehensive understanding of leveraging OpenCV for image manipulation and
harnessing the power of TensorFlow to build machine learning models.
OpenCV, originally developed by Intel and written in C++, is an open source
computer vision and machine learning library consisting of more than 2,500 optimized
algorithms for working with images and videos. TensorFlow is an open source
framework for high-performance numerical computation and large-scale machine
learning. It is written in C++ and provides native support for both CPUs and GPUs.
Python is the most widely used programming language for developing machine learning
applications. Both TensorFlow and OpenCV provide Python interfaces to access their
low-level functionality. While both TensorFlow and OpenCV also offer interfaces for
other programming languages like Java, C++, and MATLAB, we will focus on the use of
Python in this book. Python’s vast community support and intuitive syntax make it an
accessible language for learners and practitioners alike.
The prerequisites for this book are practical knowledge of Python and familiarity
with NumPy and pandas. The book assumes that you are familiar with built-in data
containers in Python, such as dictionaries, lists, sets, and tuples. If you need to brush up
on these prerequisites, the following resources can be helpful:
• Python: https://www.w3schools.com/python/
• pandas: https://pandas.pydata.org/docs/getting_started/
index.html
• NumPy: https://numpy.org/devdocs/user/quickstart.html
1
© Shamshad Ansari 2023
S. Ansari, Building Computer Vision Applications Using Artificial Neural Networks,
https://doi.org/10.1007/978-1-4842-9866-4_1
Chapter 1 Prerequisites and Software Installation
The first order of business is to prepare your working environment for the exercises
presented throughout this book. You will begin by downloading and installing the
necessary software libraries and packages.
$ python3 --version
The output of this command should be something like this: Python 3.8.10.
To check the version number of PIP, execute the following command on your
terminal:
$ pip3 --version
This command should show a version number of PIP 3, for example, PIP 20.0.2.
2
Chapter 1 Prerequisites and Software Installation
brew update
brew install python
Make sure long paths are enabled on Windows. Here are the instructions to
do that: https://www.thewindowsclub.com/how-toenable-or-disable-win
32-long-paths-in-windows-11-10.
Install the 64-bit Python 3 release for Windows from https://www.python.org/
downloads/windows/ (select PIP as an optional feature).
If these installation instructions do not work in your situation, refer to the official
Python documentation at https://www.python.org/.
3
Chapter 1 Prerequisites and Software Installation
virtualenv
virtualenv is a tool designed to create isolated Python environments. When you use
virtualenv, it generates a directory that includes all the necessary executables for utilizing
the packages required by a Python project. virtualenv provides the following advantages:
Next, we will install virtualenv and set up the virtual environment with all the
necessary software. The rest of the book assumes that the dependencies for our
reference program will be contained in this virtualenv.
After the installation is complete, create a directory of your choice where you intend
to set up the virtualenv. For purposes of following the examples in this book, name this
directory cv (short for “computer vision”):
$ mkdir cv
4
Chapter 1 Prerequisites and Software Installation
The following is a sample output from running this command (on my MacBook):
When virtualenv is active, your shell prompt is prefixed with (cv). Here’s an example:
Installing packages within a virtual environment does not affect the host system
setup. Start by upgrading PIP as follows. Please note that you should not execute any
command as root or sudo while inside the virtual environment.
When you have finished your programming activities and you want to exit from
virtualenv, run the following:
$ deactivate
TensorFlow
TensorFlow is a widely used open source library for numerical computation and
large-scale machine learning. In the upcoming chapters, you will delve deeper into
TensorFlow and explore its capabilities. However, before we proceed, let’s begin by
installing TensorFlow and preparing it for our deep learning exercises. If you have a
GPU in your computer and you want to utilize it for deep learning tasks, you typically
don’t need to install both CPU and GPU versions of TensorFlow. You can install the GPU
version, which includes support for both GPU and CPU computation. TensorFlow with
GPU support automatically falls back to CPU execution when GPU resources are not
5
Chapter 1 Prerequisites and Software Installation
available or when the operations are not suitable for GPU acceleration. So, installing
TensorFlow with GPU support (tensorflow-gpu) should be sufficient. It will work on both
GPU and CPU, making it a versatile choice for most deep learning tasks.
$ sh Downloads/Miniconda3-latest-MacOSX-arm64.sh
$ conda activate cv
$ conda deactivate
7. Activate the virtual environment by running the command conda
activate cv, and then install TensorFlow by executing the
following commands:
6
Chapter 1 Prerequisites and Software Installation
10. If you encounter any errors, resolve incompatibility issues by, for
example, upgrading the Mac OS.
If TensorFlow is successfully installed, the output should not show any errors.
1. Ensure that you have the appropriate NVIDIA GPU and drivers
installed on your system. You can check the TensorFlow
documentation for the specific GPU requirements and compatible
driver versions.
7
Chapter 1 Prerequisites and Software Installation
PyCharm IDE
For consistency, the integrated development environment (IDE) used throughout this
book for writing and managing Python code is the community version of PyCharm, a
popular Python IDE. You can choose to use your preferred IDE, but if you do so, you’ll
need to adapt relevant examples and exercises to your IDE.
Installing PyCharm
To acquire PyCharm from its official website, follow these steps:
1. Visit the PyCharm website at https://www.jetbrains.com/
pycharm/download/.
Here are the direct download links for different operating systems:
• Linux: https://www.jetbrains.com/pycharm/download/download-
thanks.html?platform=linux&code=PCC
• Mac: https://www.jetbrains.com/pycharm/download/download-
thanks.html?platform=mac&code=PCC
• Windows: https://www.jetbrains.com/pycharm/download/
download-thanks.html?platform=windows&code=PCC
Please note that these links may change over time, so it’s recommended to visit the
official PyCharm website to ensure you access the most up-to-date download links.
9
Chapter 1 Prerequisites and Software Installation
Optionally, you can select the checkbox “Make available to all projects” if you want
this interpreter to be accessible for all your projects in PyCharm.
By following these steps, you will configure PyCharm to use the virtual environment
cv as the Python interpreter for your project.
OpenCV
OpenCV is one of the most popular and widely used libraries for image processing. All
code examples in this book are based on OpenCV 4. Therefore, the installation steps
presented in this section are for version 4 of OpenCV.
10
Chapter 1 Prerequisites and Software Installation
$ source cv/bin/activate
Once the installation is complete, you can verify it by importing OpenCV in your
Python command:
If there are no errors, it indicates that OpenCV has been successfully installed.
11
Chapter 1 Prerequisites and Software Installation
Note Package names for OpenCV may vary slightly based on your specific
operating system or Python version. If you encounter any issues during the
installation, refer to the official OpenCV documentation or the PyPI page for the
most accurate and up-to-date installation instructions.
Additional Libraries
SciPy and Matplotlib are two additional libraries that we will need as we work on some
of the examples. Let’s install and keep them in our virtualenv.
Installing SciPy
Install SciPy with the following:
Installing Matplotlib
Install Matplotlib with the following:
Summary
The following table summarizes the installation commands for the required libraries
within your virtualenv. You can copy and paste these commands into your terminal to
install the libraries.
12
Chapter 1 Prerequisites and Software Installation
Ensure that your virtualenv is activated before running these commands. Once
you’ve installed these libraries, you’ll have all the necessary dependencies within your
virtualenv to work with the examples in the book.
13
CHAPTER 2
• To learn how pixels are organized in an image and how to access and
manipulate them
Image Processing
Image processing is a method used to manipulate a digital image to obtain an improved
image or extract valuable information from it. It involves taking an image as input
and producing as output either another image or specific characteristics and features
associated with that image. Videos, being composed of a series of images or frames, can
also be processed using image processing techniques. In this chapter, we will delve into
the fundamental concepts of digital image processing. Additionally, you will acquire the
basic skills to work with images and write code to manipulate them.
15
© Shamshad Ansari 2023
S. Ansari, Building Computer Vision Applications Using Artificial Neural Networks,
https://doi.org/10.1007/978-1-4842-9866-4_2
Chapter 2 Core Concepts of Image and Video Processing
Image Basics
A digital image is an electronic representation of an object/scene or scanned document.
The digitalization of an image means converting it into a series of numbers and storing
these numbers in a computer storage system. Understanding how these numbers are
arranged and how to manipulate them is the primary objective of this chapter. This
chapter explains the fundamental components that make up an image and guides you
through the process of manipulating images using OpenCV and Python.
Pixels
An image can be visualized as a collection of dots arranged in rows and columns, where
each dot represents a pixel with a specific color. These pixels are assigned numerical
values, which determine their respective colors. You can imagine an image as a grid
of square cells, where each cell corresponds to a single pixel with a specific color. For
instance, if we have a 300×400-pixel image, it implies that the image is structured as a
grid with 300 rows and 400 columns, resulting in a total of 120,000 pixels.
Pixel Color
A pixel can be represented in two different ways: grayscale and color.
Grayscale
In a grayscale image, each pixel takes a value between 0 and 255. The value 0 represents
black, and 255 represents white. The values in between are varying shades of gray. The
values close to 0 are darker shades of gray, and values closer to 255 are brighter shades
of gray.
Color
The RGB (which stands for Red, Blue, and Green) color model is one of the most popular
color representations of a pixel. Other color models are available, but this book primarily
focuses on the RGB color model.
16
Chapter 2 Core Concepts of Image and Video Processing
In the RGB model, each pixel is represented as a tuple of three values, generally
represented as follows: (value for red component, value for green component, value for
blue component). Each of the three colors is represented by integers ranging from 0 to
255. Here are some examples:
The W3Schools website is a great place to play with different combinations of RGB
tuples to explore more patterns (https://www.w3schools.com/colors/colors_rgb.asp).
Use the RGB Calculator to explore what color is represented by each of the following tuples:
(0,0,255)
(255,255,255)
(0,0,128)
(128,0,128)
(128,128,0)
Now try to make the color yellow. Here is a clue: red and green make yellow. That
means a pure red (255), a pure green (255), and no blue (0) will make yellow. So, the RGB
tuple for yellow is (255,255,0).
Now that you have a good understanding of pixels and their color, let’s explore how
pixels are arranged in an image and how to access them. The following section discusses
the concept of coordinate systems in image processing.
Coordinate Systems
As previously mentioned, pixels in an image are arranged in the form of a grid that is
made of rows and columns. Imagine a square grid of eight rows and eight columns. This
forms an 8×8 or 64-pixel image. Think of it as a 2D coordinate system in which the origin
(0,0) is the top-left corner. Figure 2-1 shows our example 8×8-pixel image.
17
Chapter 2 Core Concepts of Image and Video Processing
With the top-left corner as the start or origin of the image coordinate system, the
pixel at the top-right corner is represented by (0,7), the bottom-left pixel is (7,0), and the
bottom-right pixel is (7,7). This may be generalized as (x,y), where x is the position of the
cell from the left edge of the image and y is the vertical position down from the top edge
of the image. In Figure 2-1, the red pixel is in the fifth position from the left and fourth
from the top. Since the coordinate system begins at 0, the coordinate of the red pixel
shown in Figure 2-1 is (4,3).
To make this concept a little clearer, consider Figure 2-2, an image that is 8×8 pixels,
with the letter H written on it. Also, for simplicity, assume this is a grayscale image, with
the letter H written in black and the rest of the area of the image in white.
18
Chapter 2 Core Concepts of Image and Video Processing
So, what’s the value of the pixel at position (1,4)? And at position (2,2)?
Now, you should have a clear understanding of how images are represented as
numbers arranged in a grid. These numerical values are serialized and stored in a
computer’s storage system. When the image is displayed on the screen, these numbers
are interpreted and rendered as an actual image.
At this point, you have learned how to access individual pixels using the coordinate
system, which allows you to pinpoint specific locations within the image grid.
Additionally, you have learned how to assign colors to these pixels by manipulating their
numerical values. By grasping these concepts, you now understand how images are
structured and how to interact with them programmatically.
With a solid foundation and understanding of image representation, you are now
ready to gain practical experience through Python and OpenCV coding. In the following
section, I will guide you step-by-step through the process of writing code that loads
images from the computer’s disk, accesses individual pixels, performs manipulations,
and saves the modified images back to the disk.
Let’s delve into the exciting world of image processing and begin our hands-on journey!
19
Chapter 2 Core Concepts of Image and Video Processing
• For a grayscale image, the returned value from NumPy will be a single
value between 0 and 255.
• For a color image, the returned value from NumPy will be a tuple for
red, green, and blue. Note that OpenCV maintains the RGB sequence
in the reverse order. In other words, OpenCV stores the colors in BGR
sequence, not in RGB sequence. Remember this important feature of
OpenCV to avoid any confusion while working with OpenCV.
Before we write any code, let’s make sure we always use our virtual environment, in
the ~/cv directory, that we already set up with PyCharm in Chapter 1.
Launch your PyCharm IDE and make a new project (I named my project cviz, short
for “computer vision”). Refer to Figure 2-4 and ensure that you have selected Existing
Interpreter and have our virtualenv Python 3.8 (cv) selected.
20
Chapter 2 Core Concepts of Image and Video Processing
Figure 2-4. PyCharm IDE, showing the setup of the project with virtualenv
Filename: Listing_2_1.py
1 import cv2
2
3 # image path
4 image_path = "images/marsrover.png"
5
21
Random documents with unrelated
content Scribd suggests to you:
without fear or misgiving, it went to the judgment of Him who is
preëminently the God of battles.
In the wars of this period a common sight was that of bishops and
archbishops, clad in coats of mail, riding through the streets of their
episcopal towns on fierce chargers, and returning to their palaces
clotted with dirt and blood. That was a deserved rebuke, as well as a
fine sarcasm, with which Richard Cœur de Lion sent the blood-
stained armor of the Bishop of Beauvais to the Pope, as the garment
of Joseph to Jacob, asking the Holy Father if he recognized his son’s
coat.
Even women on occasion put on armor and mingled in the mêlée.
Gaita, the wife of Robert Guiscard, fought in the front rank of the
Normans in their conflict with the Greeks. When the crusades were
in progress many a fair woman adopted the martial costume. The
Amazonian Brunhilde is scarcely overdrawn by Scott in “Count
Robert of Paris,” and the Moslem heroines of Tasso’s “Jerusalem
Delivered,” stripped of their supernatural resources, might have
figured in the Christian camp.
Walter Scott put into the mouth of the Greek Nicephorus a pertinent
description of his fellow-Christians of the West: “To whom the strife
of combat is as the breath of their nostrils, who, rather than not be
engaged in war, will do battle with their nearest neighbors and
challenge each other to mortal fight, as much in sport as we would
defy a comrade to a chariot-race.”
It is but just to say that, if the Greeks were amazed at the warlike
propensities of the Catholics, they expressed no wonder at their
cruelty. In this they themselves even excelled their more robust
rivals. The dungeons of Constantinople were filled with political
offenders whose eyes were torn from their sockets; and more than
one imperial candidate resumed his place of honor among a people
whose waving banners he was unable to see. The Greek differed
from the Frank and German, the Norman and Saxon, chiefly in being
a coward and choosing to glut his brutal instincts with the use of the
secret torture, the poisoned cup, or the dagger in the back of his
victim, rather than with the sword and battle-axe in open fight.
To a people such as we have described the appeal for the crusades,
in which the imagined cause of heaven marched in step with their
own tastes and habits, was irresistible.
CHAPTER III.
CHIVALRY—RULES—EDUCATION OF KNIGHT—
CEREMONIES—INFLUENCE ON CHARACTER.
The call for the crusades, while appealing powerfully to the warlike
disposition of the people, would not have succeeded in rousing
Europe had there not been in the popular heart at least the germs of
nobler sentiment. The vitality of conscience notwithstanding its
degradation, and an inclination towards the exercise of the finer
graces of conduct in spite of the prevalent grossness, manifested
themselves in the rise of Chivalry.
The picturesqueness of knight-errantry, and the glamour thrown over
the subject by poetry and romance, may mislead us as to the real
character of this institution. We must distinguish between the ideals
of knighthood and the actual lives of those who, from various
motives, thronged the profession. We must not confound the
Chivalry of these earlier and ruder ages with that of its more refined,
though somewhat effeminate, later days. It would be an equal
mistake to pose the half-savage Saxon for a picture of the gallant
Provençal, because they were fellows of the same order. But,
making all allowance for variations, defects, and perversions in
Chivalry, the institution went far towards redeeming the character of
the middle ages. Among the articles of the chivalric code were the
following:
To fight for the faith of Christ. In illustration of this part of his vow, the
knight always stood with bared head and unsheathed sword during
the reading of the lesson from the gospels in the church service.
To serve faithfully prince and fatherland.
To defend the weak, especially widow’s, orphans, and damsels.
To do nothing for greed, but everything for glory.
To keep one’s word, even returning to prison or death if, having been
captured in fair fight, one had promised to do so.
Together with these vows of real virtue were others, which signified
more for the carnal pride of the warrior, e.g.:
Never to fight in companies against one opponent.
To wear but one sword, unless the enemy displayed more than one.
Not to put off armor while upon an adventure, except for a night’s
rest.
Never to turn out of a straight road in order to avoid danger from
man, beast, or monster.
Never to decline a challenge to equal combat, unless compelled to
do so by wounds, sickness, or other equally reasonable hindrance.
The aspirant for knighthood began his career in early boyhood by
attending some superior as his page. Lads of noblest families sought
to be attached to the persons of those renowned in the order, though
not to their own fathers, lest their discipline should be over-indulgent.
Frequently knights of special note for valor and skill at arms opened
schools for the training of youth. The page was expected to wait
upon his lord as a body-servant in the bedchamber, the dining-hall,
and, when consistent with his tender years, upon the journey and in
the camp. It was a maxim of the code that one “should learn to obey
before attempting to govern.”
With the development of manly strength, at about his fourteenth year
the page became an esquire. He then burnished and repaired the
armor of his chief, broke his steeds, led his charger, and carried his
shield to the field of battle. In the mêlée he fought by his master’s
side, nursed him when wounded, and valued his own life as naught
when weighed against his lord’s safety or honor.
The faithful esquire was adubbed a knight at the will and by the hand
of his superior. This honor was sometimes awarded on the field of
conflict for a specially valiant deed. More commonly the heroic
subalterns were summoned to receive the coveted prize when the
fight was done. More than one instance is mentioned where the
esquire bowed his head beneath the dead hand of his master and
there assumed the duty of completing the enterprise in which his
chief had fallen. Ordinarily, however, the ceremony was held in the
castle hall, or in later times in the church, on the occasion of some
festival or upon the candidate’s reaching the year of his majority.
The rite of admission to knighthood was made as impressive as
possible. The young man, having come from the bath, was clothed in
a white tunic, expressive of the purity of his purpose; then in a red
robe, symbolical of the blood he was ready to shed; and in a black
coat, to remind him of the death that might speedily be his portion.
After fasting, the candidate spent the night in prayer. In the morning
the priest administered to him the holy communion, and blessed the
sword which hung from his neck. Attendant knights and ladies then
clothed him in his armor. Kneeling at the feet of the lord, he received
from him the accolade, three blows with the flat of the sword upon
his shoulder, with the repetition of the formula, “In the name of God,
St. Michael, and St. George, I make thee a knight.”
More impressive, because more unusual, was the ceremony of his
degradation, if he broke his plighted faith or forfeited his honor. He
was exposed on a platform, stripped of his armor, which was broken
to pieces and thrown upon a dunghill. His shield was dragged in the
dirt by a cart-horse, his own charger’s tail was cut off, while he was
himself carried into a church on a litter, and forced to listen to the
burial service, since he was now to move among men as one who
was dead to the honor for which he had vowed to live.
The chief defect of Chivalry was that, while it displayed some of the
finer sentiments of the soul in contrast with the general grossness of
the age, it did not aspire to the highest motives as these were felt in
the early days of Christianity and as they are again apprehended in
modern times. Notwithstanding the vow of devotion, there was little
that was altruistic about it. The thought of the devotee was ultimately
upon himself, his renown and glory. His crested helmet, his gilded
spurs, his horse in housing of gold, and the scarlet silk which marked
him as apart from and above his fellows, were not promotive of that
humility and self-forgetfulness from which all great moral actions
spring. Our modern characterization of the proud man is borrowed
from the knight’s leaving his palfrey and mounting his charger, or, as
it was called, getting “on his high horse.” In battle the personality of
the knight was not, as in the case of the modern soldier, merged in
the autonomy of the brigade or squadron; he appeared singly
against a selected antagonist of equal rank with his own, so that the
field presented the appearance of a multitude of private combats. In
the lull of regular warfare he sought solitary adventures for gaining
renown, and often challenged his companions in arms to contest
with him the palm of greater glory. Writers aptly liken the mediæval
knights to the heroic chiefs of Arabia, and even of the American
Indians, to whom personal prowess is more than patriotism. Hallam
would choose as the finest representative of the chivalric spirit the
Greek Achilles, who could fight valiantly, or sulk in his tent regardless
of the cause, when his individual honor or right seemed to be
menaced.
The association of Chivalry with gallantry, though prompted by the
benevolent motive of helping the weak or paying homage to woman
as the embodiment of the pure and beautiful, did not always serve
these high purposes. The “love of God and the ladies,” enjoined as a
single duty, was often to the detriment of the religious part of the
obligation. The fair one who was championed in the tournament was
apt to be sought beyond the lists. The poetry of the Troubadours
shows how the purest and most delicate sentiment next to the
religious, the love of man for woman, became debauched by a
custom which flaunted amid the brutal scenes of the combat the
name of her whose glory is her modesty, and often made her virtue
the prize of the ring.
Doubtless the good knight felt that the altar of his consecration was
not high enough. Even his vow to defend the faith had, within the
bounds of Christendom, little field where it could be honored by
exploit of arms. To take his part in the miserable quarrels that were
chronic between rival popes, or in the wars of the imperial against
the prelatic powers, both professedly Christian, could not satisfy any
really religious desires he may have felt. The chivalric spirit thus
kindled the aspiration for an ideal which it could not furnish. If the
soldier of the cross must wear armor, he would find no satisfaction
unless he sheathed his sword in the flesh of the Infidels, whose
hordes were gathering beyond the borders of Christendom. The
institution of Chivalry thus prepared the way for the crusades, which
afforded a field for all its physical heroism, while at the same time
these great movements stimulated and gratified what to this
superstitious age was the deepest religious impulse.
CHAPTER IV.
THE FEUDAL SYSTEM—GENERAL PRINCIPLES—
INFLUENCE ON PEOPLE.
The once luxuriant civilization of Rome had been swept away by the
Northern invaders as completely as a freshet despoils the fields
when it not only destroys standing vegetation, but carries with the
débris the soil itself. The most primitive arts, those associated with
agriculture, were forgotten, and the rudiments of modern industries
were not thought of. Much of the once cultivated land had, as has
elsewhere been noted, reverted to native forest and marsh, and in
places was still being purchased by strangers on titles secured by
occupancy and first improvement, as now in the new territories of
America. But even nature’s pity for man was outraged; the bounty
she gave from half-tilled acres was despoiled by men themselves, as
hungry children snatch the morsels of charity from one another’s
hands. What was hoarded for personal possession became the spoil
of petty robbers, and what was left by the neighborhood marauder
was destroyed in the incessant baronial strife. To these devouring
forces must be added the desolating wars between the papal and
imperial powers, the conquest and reconquest of Spain by Moors
and Christians, and the despoiling of Saxon England by the
Normans. Throughout Europe, fields, cottages, castles, oftentimes
churches, were stripped by the vandalism which had seemingly
become a racial disposition. To this ordinary impoverished condition
was added the especial misery, about 1195, of several years’ failure
of crops. Famine stalked through France and middle Europe; villages
were depopulated. Cruel as they were, men grew weary of raiding
one another’s possessions when there was nothing to bring back but
wounds. Even hatred palled when unsupported by envy and cupidity.
The crusades gave promise of opening a new world to greed. The
stories that were told of Eastern riches grew, as repeated from
tongue to tongue, until fable seemed poor in comparison with what
was believed to be fact. All the wealth of antiquity was presumed to
be still stored in treasure-vaults, which the magic key of the cross
would unlock. The impoverished baron might exchange his half-
ruined castle for some splendid estate beyond the Ægean, and the
vulgar crowd, if they did not find Jerusalem paved with gold like the
heavenly city, would assuredly tread the veins of rich mines or rest
among the flowers of an earthly paradise. The Mohammedan’s
expectation of a sensual heaven after death was matched by the
Christian’s anticipation of what awaited him while still in life.
They who were uninfluenced by this prospect may have seized the
more warrantable hope of opening profitable traffic with the Orient.
The maritime cities of Italy had for a long time harvested great gains
in the eastern Mediterranean, in spite of the Moslem interruptions of
commerce. Would not a tide of wealth pour westward if only the
swords of the Christians could hew down its barriers?
The church piously, but none the less shrewdly, stimulated the sense
of economy or greed by securing exemption from taxation to all who
should enlist, and putting a corresponding burden of excise upon
those who remained at home, whose estates were assessed to pay
the expenses of the absent. The householder who found it difficult to
save his possessions while keeping personal guard over them was
assured that all his family and effects would be under the watchful
protection of the church, with anathemas already forged against any
who should molest them. If one were without means he might borrow
to the limit of his zeal, with exemption from interest. It was
understood that the Jews were still under necessity of paying back
the thirty pieces of silver with which they had bought the Christians’
Lord, the interest on which, compounded through the centuries, was
now equal in amount to all there might be in the vaults of this
accursed race.
When we remember the wars of modern times which have originated
in the cupidity of men, we are not surprised that the same
disposition, inflamed by the sense of dire need at home and the
vision of untold treasures outre mer, with heavenly rewards beyond
the sky, should have led to the same result in an age that knew
almost nothing of the arts of peace.
CHAPTER VI.
THE PAPAL POLICY—DEMORALIZATION OF THE
WORLD AND THE CHURCH—HILDEBRAND’S
PURPOSE INHERITED BY HIS SUCCESSORS.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookmass.com