Reader small image

You're reading from  Mastering OpenCV 4 with Python

Product typeBook
Published inMar 2019
Reading LevelExpert
PublisherPackt
ISBN-139781789344912
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Alberto Fernández Villán
Alberto Fernández Villán
author image
Alberto Fernández Villán

Alberto Fernndez Villn is a software engineer with more than 12 years of experience in developing innovative solutions. In the last couple of years, he has been working in various projects related to monitoring systems for industrial plants, applying both Internet of Things (IoT) and big data technologies. He has a Ph.D. in computer vision (2017), a deep learning certification (2018), and several publications in connection with computer vision and machine learning in journals such as Machine Vision and Applications, IEEE Transactions on Industrial Informatics, Sensors, IEEE Transactions on Industry Applications, IEEE Latin America Transactions, and more. As of 2013, he is a registered and active user (albertofernandez) on the Q&A OpenCV forum.
Read more about Alberto Fernández Villán

Right arrow

Assessments

Chapter 1

  1. The main purpose of Python virtual environments is to create an isolated environment for Python projects. This means that each project can have its own dependencies, regardless of what dependencies every other project has. In other words, it is an isolated working copy of Python that allows you to work on a specific project without worry of affecting other projects.
  2. The connection between pip, virtualenv, pipenv, Anaconda, and conda is as follows:
  • pip: The Python Package Manager:
    • The PyPA recommended tool for installing Python packages
    • You can find and publish Python packages using PyPI: The Python Package
      Index (https://pypi.python.org/pypi)
  • pyenv: Python Version Manager:
    • pyenv lets you easily switch between multiple versions of Python
    • If you need to use different versions of Python, pyenv lets you manage this easily
  • virtualenv: Python Environment Manager:...

Chapter 2

  1. There are three image processing steps:
    1. Getting the necessary information to work with (for example, an image or video file, among others)
    2. Processing the image by applying image processing techniques
    3. Showing the results in the required way (for example, save the image to disk, show the image, and so forth)
  2. The processing step can be broken down into three processing levels:
    1. Low-level processing
    2. Mid-level processing
    3. High-level processing

  1. A grayscale image contains for every pixel of the image a value that is proportional to the brightness or gray levels of the image. This value is also called intensity or grayscale level. This value is ∈ [0, L-1], where L = 256 (for an 8-bit image).

On the other hand, black and white images contain for every pixel of the image a value that can only take two values. Usually, these values are 0 (black) and 255 (white...

Chapter 3

  1. The second element of the list is the first argument to the script, which is sys.argv[1].
  2. The code is as follows:
parser = argparse.ArgumentParser()
parser.add_argument("first_number", help="first number to be added", type=int)
  1. The code to save the image is as follows:
cv2.imwrite("image.png", img)
  1. The capture object is created as follows:
capture = cv2.VideoCapture(0)
  1. The capture object is created as follows:
capture = cv2.VideoCapture(0)
print("CV_CAP_PROP_FRAME_WIDTH: '{}'".format(capture.get(cv2.CAP_PROP_FRAME_WIDTH)))
  1. The code to read the image is as follows:
image = cv2.imread("logo.png")
cv2.imwrite("logo_copy.png", gray_image)
  1. The script is written as follows:
"""
Example to introduce how to read a video file backwards and save it
"""

# Import the required...

Chapter 4

  1. The parameter thickness can take positive and negative values. If the value is positive, it indicates the thickness of the outline. A negative value (for example, -1) indicates that a filled shape will be drawn. For example, to draw a filled ellipse, note the following:
cv2.ellipse(image, (80, 80), (60, 40), 0, 0, 360, colors['red'], -1)

You can also use cv2.FILLED:

cv2.ellipse(image, (80, 80), (60, 40), 0, 0, 360, colors['red'], cv2.FILLED)
  1. The lineType parameter can take three values (cv2.LINE_4 == 4, cv2.LINE_AA == 16, cv2.LINE_8 == 8). To draw Anti Aliased lines, you must use cv2.LINE_AA:
cv2.line(image, (0, 0), (20, 20), colors['red'], 1, cv2.LINE_AA)
  1. The diagonal line is created with the help of the following code:
cv2.line(image, (0, 0), (512, 512), colors['green'], 3)
  1. The text is rendered as follows:
cv2.putText...

Chapter 5

  1. The cv2.split() function splits the source multi-channel image into several single-channel images,
    (b, g, r) = cv2.split(image).
  2. The cv2.merge() function merges several single-channel images into a multi-channel image, image = cv2.merge((b, g, r)).
  3. The image can be translated as follows:
height, width = image.shape[:2]
M = np.float32([[1, 0, 150], [0, 1, 300]])
dst_image = cv2.warpAffine(image, M, (width, height))

  1. The image can be rotated in the following manner:
height, width = image.shape[:2]
M = cv2.getRotationMatrix2D((width / 2.0, height / 2.0), 30, 1)
dst_image = cv2.warpAffine(image, M, (width, height))
  1. The image can be built as follows:
kernel = np.ones((5, 5), np.float32) / 25
smooth_image = cv2.filter2D(image, -1, kernel)
  1. The grayscale image is as follows:
M = np.ones(image.shape, dtype="uint8") * 40
added_image = cv2.add(image, M)
  1. COLORMAP_JET...

Chapter 6

  1. An image histogram is a type of histogram that reflects the tonal distribution of the image. It plots the frequency (number of pixels) for each tonal value (commonly in the range of [0-255]).
  2. In OpenCV, we make use of the cv2.calcHist() function to calculate the histogram of images. To calculate the histogram of a grayscale image using 64 bits, the code is as follows:
 hist = cv2.calcHist([gray_image], [0], None, [64], [0, 256])
  1. We first build the image, M, with the same shape as the grayscale image, gray_image, and we set the value, 50, for every pixel of this image. Afterwards, we add both images using cv2.add(). Finally, the histogram is computed using cv2.calcHist():
M = np.ones(gray_image.shape, dtype="uint8") * 50
added_image = cv2.add(gray_image, M)
hist_added_image = cv2.calcHist([added_image], [0], None, [256], [0, 256])
  1. In a BGR image, the red...

Chapter 7

  1. ret, thresh = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)
  2. thresh = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 2)
  3. ret, th = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
  4. ret, th = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_TRIANGLE)
  5. Otsu's thresholding using scikit-image can be applied as follows:
thresh = threshold_otsu(gray_image)
binary = gray_image > thresh
binary = img_as_ubyte(binary)

Remember that the threshold_otsu(gray_image) function returns the threshold value based on Otsu's binarization algorithm. Afterwards, with this value, the binary image is constructed (dtype= bool), which should be converted into an 8-bit unsigned integer format (dtype= uint8) for proper visualization. The img_as_ubyte() function is used for this purpose.

  1. Triangle...

Chapter 8

  1. The cv2.findContours() function finds contours in a binary image (for example, the resulting image after a thresholding operation).
  2. The four flags OpenCV provides for compressing contours are as follows:
  • cv2.CHAIN_APPROX_NONE
  • cv2.CHAIN_APPROX_SIMPLE
  • cv2.CHAIN_APPROX_TC89_KCOS
  • cv2.CHAIN_APPROX_TC89_L1
  1. The cv2.moments() function calculates all of the moments up to the third order of a polygon or rasterized shape.
  2. The moment, m00, gives the area of the contour.
  3. OpenCV provides the cv2.HuMoments() function to calculate the seven Hu moment invariants.
  4. The cv2.approxPolyDP() function returns a contour approximation of the given contour based on the given precision. This function uses the Douglas-Peucker algorithm. The epsilon parameter specifies the precision for establishing the maximum distance between the original curve and its approximation.
  5. The extreme_points() function...

Chapter 9

  1. Keypoints and compute descriptors in the loaded image, image, with ORB are as follows:
orb = cv2.ORB()
keypoints = orb.detect(image, None)
keypoints, descriptors = orb.compute(image, keypoints)

  1. Previously detected keypoints, keypoints, are as follows:
image_keypoints = cv2.drawKeypoints(image, keypoints, None, color=(255, 0, 255), flags=0)

To draw detected keypoints, the cv2.drawKeypoints() function is used.

  1. The BFMatcher object and matching of the descriptors, descriptors_1 and descriptors_2, which have been previously calculated, is created as follows:
bf_matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
bf_matches = bf_matcher.match(descriptors_1, descriptors_2)
  1. The first 20 matches of the matches that were sorted before is as follows:
bf_matches = sorted(bf_matches, key=lambda x: x.distance)
result = cv2.drawMatches(image_query, keypoints_1, image_scene...

Chapter 10

  1. In the context of machine learning, there are three main approaches and techniques: supervised, unsupervised, and semi-supervised machine learning.
  2. Supervised learning problems can be further grouped into regression and classification problems. A classification problem happens when the output variable is a category, and a regression problem is when the output variable is a real value. For example, if we predict the possibility of rain in some regions and assign two labels (rain/no rain), this is a classification problem. On the other hand, if the output of our model is the probability associated with the rain, this is a regression problem.
  3. OpenCV provides the cv2.kmeans() function, implementing a k-means clustering algorithm, which finds centers of clusters and groups input samples around the clusters. k-means is one of the most important clustering algorithms available...

Chapter 11

  1. We have seen four libraries and packages: OpenCV library, but also the dlib (http://dlib.net/python/index.html, https://pypi.org/project/dlib/, https://github.com/davisking/dlib), face_recognition (https://pypi.org/project/face_recognition/, https://github.com/ageitgey/face_recognition), and cvlib (https://pypi.org/project/cvlib/, https://github.com/arunponnusamy/cvlib, https://www.cvlib.net/) Python packages.
  2. Face recognition, which is a specific case of object recognition, where a person is identified or verified from an image or video using the information extracted from the face, can be decomposed into face identification and face verification:
  • Face verification is a 1:1 matching problem that tries to answer the question: Is this the claimed person? For instance, unlocking a mobile phone using your face is an example of face verification.
  • Face identification...

Chapter 12

  1. Three main differences between machine learning and deep learning are as follows:
  • Deep learning algorithms need to have a high-end infrastructure to train properly. Deep learning techniques heavily rely on high-end machines, contrary to traditional machine learning techniques, which can work on low-end machines.
  • When there is a lack of domain understanding for both feature introspection and engineering, deep learning techniques outperform other techniques because you have to worry less about feature engineering.
  • Both machine learning and deep learning are able to handle massive dataset sizes, however machine learning methods make much more sense when dealing with small datasets. A rule of thumb is to consider that deep learning outperforms other techniques if the data size is large, while traditional machine learning algorithms are preferable when the dataset is...

Chapter 13

  1. Web frameworks can be categorized into full-stack and non full-stack frameworks. Django (https://www.djangoproject.com/) is a full-stack web framework for Python, while Flask (http://flask.pocoo.org/) is a non full-stack framerwork for Python.
  2. In Flask, you can use the route() decorator to bind a function to a URL. In other words, the route() decorator is used to indicate to Flask what URL should trigger a specific function.
  3. To make the server publicity available, the host=0.0.0.0 parameter should be added when running the server application:
if __name__ == "__main__":
# Add parameter host='0.0.0.0' to run on your machines IP address:
app.run(host='0.0.0.0')

  1. The jsonify() function is used to create the JSON representation of the given arguments with an application/json mimetype. JSON can be considered the de facto standard for...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering OpenCV 4 with Python
Published in: Mar 2019Publisher: PacktISBN-13: 9781789344912
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Alberto Fernández Villán

Alberto Fernndez Villn is a software engineer with more than 12 years of experience in developing innovative solutions. In the last couple of years, he has been working in various projects related to monitoring systems for industrial plants, applying both Internet of Things (IoT) and big data technologies. He has a Ph.D. in computer vision (2017), a deep learning certification (2018), and several publications in connection with computer vision and machine learning in journals such as Machine Vision and Applications, IEEE Transactions on Industrial Informatics, Sensors, IEEE Transactions on Industry Applications, IEEE Latin America Transactions, and more. As of 2013, he is a registered and active user (albertofernandez) on the Q&A OpenCV forum.
Read more about Alberto Fernández Villán