Contents:

Course with employment: “Profession Data scientist»
Learn moreWhen teaching young children, parents use books with bright and colorful illustrations, such as cats, flowers, and cars. These bright images help children recognize and distinguish objects, developing their visual perception and cognitive skills. Using such books promotes the formation of basic concepts and improves the child's vocabulary, which is an important stage in their development.
Computers learn to recognize images using much more data than humans do. This process is accomplished using a technology known as computer vision. Computer vision allows machines to analyze and interpret visual information, which opens up new possibilities for automation and increasing the efficiency of various processes.
- How computer vision works
- What is OpenCV
- Where computer vision and OpenCV are used
- How to work with OpenCV in Python
- Installing OpenCV
- How OpenCV sees images
- Reading, display modes and writing
- Changing pixel color
- Resizing an image
- Cropping
- Rotating
- Examples of OpenCV scripts
- Displaying point coordinates
- Face recognition
- What's next
How computer vision works Computer vision is an important field of artificial intelligence focused on acquiring, processing, and analyzing visual information, including images and video. This technology has wide applications in various fields, such as medicine, security, autonomous vehicles, and industry. Advances in computer vision enable improved data analysis, automated processes, and increased efficiency across various industries. Modern algorithms and machine learning methods facilitate more accurate recognition of objects and scenes, opening up new horizons for innovative solutions.
Let's look at a specific example to illustrate this definition. Look at the image and describe what you see in it.

The gaze is drawn to individual objects. A pair of sunglasses reflects a person holding a red pill in one lens, while the other lens reflects the same person holding a blue pill in the other. This contrast between the red and blue pills creates a sense of choice and symbolizes the different paths one can take in life.
The Matrix is one of the most famous films in the world of cinema. If you are familiar with the film, you can easily name it, recognize the main characters, and perhaps recall the names of the actors who played key roles. Your level of familiarity with the film often depends on your passion for cinema and the number of films you've seen. The Matrix has left a significant mark on pop culture and continues to inspire audiences and filmmakers around the world.
A program's perception of an image depends on its algorithms and database, as well as the complexity of the code used. The program analyzes visual elements based on available information and predefined rules, which determines its interpretation and the ability to recognize objects.
- A simple program will only be able to recognize that it is a file with the .jpg extension—that is, an image.
- A more complex program will open the file and understand that it consists of a set of pixels of different colors. It will be able to display the image on the screen and possibly even edit it: change the color of some pixels to a different one, crop the image, and so on.
- If the program uses neural networks, it will analyze the image and extract additional information from it, beyond the technical one: it will determine where glasses, hands, pills, and faces are in the picture, find similar images, and recognize the movie the frame is from and which actors are in it. This is computer vision. The set of extracted information will depend on what the program has been trained to do.
Machine learning is used to enable the program to analyze an image not just as a set of pixels, but as a collection of known objects. This method allows the system to recognize and classify objects in images, improving its ability to perceive visual information. The use of machine learning algorithms in image processing opens up new possibilities for automating and improving the accuracy of visual data analysis.

Read also:
Machine learning, or machine learning, is a field of artificial intelligence focused on developing algorithms that can learn from data and improve its performance over time. It is a technology that allows computers to recognize patterns and make predictions without explicit programming.
The study of machine learning is becoming increasingly relevant in the modern world, as it finds application in various fields, such as medicine, finance, marketing, and many others. With machine learning, companies can analyze large amounts of data, optimize processes, improve user experiences, and make more informed decisions.
There are many resources for learning machine learning, including online courses, books, and specialized communities. If you are planning a career in technology, studying machine learning will open new opportunities for you and increase your competitiveness in the job market. This knowledge will be a valuable asset in the context of rapid digital development and increasing data volumes.
Computer vision and machine vision are two related concepts, but their applications differ. Machine vision is a specialized use of computer vision technologies to solve specific problems. For example, cameras are installed on production lines to monitor the quality of products on the conveyor. If the camera detects a defect, it signals the operator to intervene. Machine vision thus focuses on narrow tasks, in contrast to the broader approach of computer vision, which covers a variety of applications, including object recognition, image analysis, and process automation.
What is OpenCV
OpenCV (Open Source Computer Vision Library) is a powerful open-source library designed for computer vision tasks. It was originally developed in C++, but is now available for use in languages such as Python, C, Java, and MATLAB. OpenCV provides a wide range of tools and algorithms for image and video processing, making it a popular choice among both researchers and developers. OpenCV can be used to implement projects in the fields of face recognition, object tracking, as well as machine learning and artificial intelligence.
OpenCV offers a set of built-in computer vision algorithms based on machine learning. These algorithms are presented as separate modules, each with unique functionality. Among them, there are several key solutions that significantly simplify the tasks of image processing and video analysis.
- Core Functionality (core functionality) - defines the main data structures and library functions that are used in other modules.
- Image Processing (image processing) - allows you to work with static images: simple pictures in PNG, JPG and other formats.
- Video Analysis (video analysis) - is used to track the movement of objects and work with the background.
- Camera Calibration and 3D Reconstruction (camera calibration and 3D reconstruction) - works with the geometry of objects, allowing you to create their 3D models based on multiple images or videos.
- 2D Features Framework (2D Features Framework) - identifies fragments of an image that are different from others by remembering their contours, and can find similar ones among them.
- Object Detection (object detection) - finds objects such as faces, cars, birds, etc. other.
- High-level GUI — allows you to draw graphical interfaces for performing simple operations.
- Video I/O — allows you to read and process video files.
This is just a small selection of OpenCV modules. For more detailed information about them, as well as other library features, we recommend reading the official documentation. OpenCV offers a wide range of tools for image processing and computer vision, making it indispensable in various fields such as machine learning, video analysis, and object recognition.
Where computer vision and OpenCV are used
Computer vision has become an integral part of our daily lives. It is used in robotic vacuum cleaners that effectively avoid obstacles, as well as in modern cars that can independently drive and avoid collisions. Furthermore, social media is using computer vision technology to recognize faces in photos, asking if it's really you. These advances demonstrate how computer vision is transforming various industries, improving the convenience and safety of our lives.
Computer vision is used to solve a variety of problems, including object recognition, image and video analysis, and process automation. This technology is widely used in various fields, such as medicine, security, automotive, and manufacturing. The use of computer vision significantly increases the efficiency and accuracy of visual information processing, which contributes to the development of innovative solutions and improves quality of life.
Text recognition on mobile devices has become accessible thanks to modern applications. For example, to translate labels, simply open a translator app and point the camera at the text. The program will automatically recognize the text and provide a translation into the desired language. This is convenient and effective, especially in situations where you need to quickly understand information in a foreign language. Using text recognition technology significantly simplifies communication and helps in everyday life, making international travel more comfortable.
Image search allows you to quickly identify unfamiliar flowers. Simply take a photo of the plant and upload it to search engines such as Google or Yandex. These platforms use image recognition technology to provide information about the name and characteristics of the flower. This search method is convenient and effective for botanists and plant enthusiasts looking to expand their knowledge of flora.
Content moderation is an important component of many forums and social networks. These platforms use automated systems to analyze uploaded content and remove it if it violates established rules. The moderation process helps maintain order and security in online communities and protects users from unwanted information. Effective moderation helps create a comfortable environment for communication and exchange of opinions, which makes the platforms more attractive to users.
Biometric data allows you to unlock your phone or access services using your fingerprint or facial recognition. Your data is processed using computer vision algorithms, providing a high level of security and convenience. Biometrics is becoming an essential tool in modern technology, facilitating access to devices and protecting personal information.
The creation of 3D models has become possible thanks to computer vision, which allows you to generate three-dimensional objects from multiple photographs or videos. This technology is widely used in restoring the appearance of objects and landscapes. In the field of robotics, 3D modeling helps robots navigate in space, improving their navigation and interaction with the environment. Using computer vision to create 3D models opens up new horizons in various fields, such as architecture, design, and virtual reality.
The development of agriculture with the use of computer vision opens up new possibilities for efficient resource management. Computer vision technologies make it possible to accurately count livestock and monitor crops. They can be used to assess plant health and identify pests and diseases at an early stage, significantly increasing yields and reducing the risk of loss. Implementing such solutions helps agronomists and farmers make more informed decisions, optimizing agricultural processes and increasing overall production efficiency. Production Management: Instead of relying on humans to perform routine tasks, computer vision technologies can independently analyze products and processes. Installing cameras on conveyors allows for the prompt identification of defective products. Such a system is not susceptible to fatigue or distraction, significantly increasing the effectiveness of quality control on the production line. The implementation of computer vision in production processes helps reduce errors and increase productivity, ensuring a high level of reliability and accuracy. Many tools exist for developing computer vision systems, and one of the most popular is OpenCV. This library tool is actively used by such tech giants as Google, Yahoo, Microsoft, Intel, IBM, Sony, Honda, and Toyota. OpenCV provides powerful capabilities for processing images and video, allowing you to effectively solve a wide range of computer vision problems.
OpenCV is actively used in various fields, including monitoring the condition of equipment in mines in China and facial recognition in Japan. You can also create a facial recognition program. In this guide, we will share the basic steps to help you develop such a program.
How to Work with OpenCV in Python
The OpenCV library is a free tool available for use in personal, educational, and commercial projects. In this overview, we will examine the main features of OpenCV using the Python programming language as an example and develop a script that will recognize people's faces.
To run OpenCV, you need to install one of the supported programming languages, in this case, Python. If Python is not yet installed on your computer, you can refer to our guide for installing it. With Python installed, you can effectively use the OpenCV library for image and video processing.
The library can be downloaded using your integrated development environment (IDE) tools or via the command line.
Import the module and start working with it.
Before moving on to practical applications, it's important to understand how OpenCV processes images. This library treats images as NumPy arrays. This allows for efficient pixel manipulation and various operations, such as filtering, transformation, and image analysis. Understanding how to work with NumPy arrays is key to successfully using OpenCV for image processing tasks.

Read also:
NumPy Library: Key Aspects for Beginners
NumPy is one of the most popular libraries for working with arrays and matrices in the Python programming language. It provides convenient tools for performing numerical calculations and data processing. Beginners to NumPy should understand the basic concepts and capabilities of this library.
NumPy's core object is multidimensional arrays, which allow you to efficiently store and process large amounts of data. NumPy also supports vectorized operations, which significantly speeds up calculations compared to standard Python loops.
The library includes many functions for performing mathematical operations, such as addition, multiplication, matrix multiplication, and calculating statistical indicators. For working with arrays, NumPy offers various methods for changing the dimension, extracting subarrays, and performing slicing.
Furthermore, NumPy integrates with other libraries such as SciPy and Pandas, making it an indispensable tool for data analysis and scientific computing. By mastering the basics of NumPy, beginning programmers can significantly improve their productivity in the fields of data analysis and machine learning.
Learning NumPy opens the door to more advanced concepts such as linear algebra and multivariate data handling, making it an important step towards developing professional skills in programming and data analysis.
A grayscale image is represented as a two-dimensional array. Each pixel in the image is encoded as a number from 0 to 255, where 0 corresponds to black, 255 to white, and values in between represent different shades of gray. This approach allows images to be efficiently stored and processed using a minimal amount of data to represent color information.
Each pixel row is represented as a one-dimensional array. For example, the array [255, 255, 77, 77, 77, 255, 255] consists of seven pixels, including two white, three gray, and two white. This data representation method enables efficient processing and analysis of graphic information, simplifying work with digital images.
Each pixel row is organized into a second-level array. For example, this array contains data about the color and brightness of pixels, enabling efficient image processing and display. Using arrays to store pixel information ensures rapid data accessibility and optimized graphics processing. This is especially important in the context of developing visual applications and games, where performance plays a key role.
As a result, we get a reduced image that is 100 times smaller than the original.

Working with color images requires using a three-dimensional array. The color of each pixel is represented by three values ranging from 0 to 255, which corresponds to the RGB model. In this model, the order of the colors is reversed: the first number corresponds to blue, the second to green, and the third to red, which forms the BGR model.
Examples of pixels of various colors in the OpenCV language demonstrate the capabilities of working with images and colors in this library. OpenCV makes it easy to manipulate pixels, change their color values, and perform image analysis. Primary colors such as red, green, and blue can be represented in the BGR format, which is the standard for OpenCV. Learning to work with pixels and their colors allows developers to create effective algorithms for image processing, object recognition, and computer vision. Using OpenCV in image processing projects opens up a wide range of possibilities for developers and researchers in computer science and technology.
- [0, 0, 0] — black.
- [255, 255, 255] — white.
- [255, 0, 0] — blue.
- [0, 255, 0] — green.
- [0, 0, 255] — red.
- [0, 255, 255] — yellow.
- [203, 192, 255] — pink.
A table of common RGB colors can be found here. Please note that in the OpenCV library, the color order is reversed: the first and third colors are swapped.
As with grayscale images, the next-level multidimensional array combines rows of pixels, while the top-level array represents the full image. This approach ensures efficient data storage and processing, which is especially important for graphics applications and computer vision. Optimizing the data structure allows for rapid retrieval and analysis of information, improving the performance of image processing algorithms.
In OpenCV, an array representing an image consisting of nine colored pixels would look like this:
The image is presented in an enlarged format for your convenience. This allows you to better examine details and features, which is especially important when analyzing or evaluating the content of the image. Enlarged images help users examine the presented material more closely, which can be useful in various contexts, such as learning, work, or creativity. Consider using larger images to enhance the visual experience.

Download any image, preferably bright and high-contrast, and open it in your code. This will help improve the visual appeal of your content and attract visitors' attention. Vibrant images can significantly increase interest in your website and improve its SEO rankings. We present an example image that illustrates the key points of our topic. This image will help you better understand the materials and ideas we're covering. Such visual elements play a crucial role in information comprehension and make content more accessible to the audience. Using high-quality images helps improve SEO, as they increase user time on page and reduce bounce rates. We recommend paying attention to the quality and relevance of images so that they harmoniously complement the text and enhance its meaning.

Examine the image and open it in a new window for better viewing.
- cv2.imread — "reads" an image and returns a NumPy array that the library can work with. It receives a full or relative path to the image as an argument.
- cv2.imshow — opens an image in a separate operating system window. The first argument is the window name, the second is a NumPy array, in our case it is stored in the image variable.
- cv2.waitKey — if you do not specify this function, the open window will close immediately. It receives a button that must be pressed to close the window. If you specify 0, the window will close when any button is pressed.
The cv2.imread function in the OpenCV library allows you to load images and takes an optional second argument, which determines their display mode. This argument can be used to specify how exactly the image should be interpreted when loading. For example, you can choose to display the image in color, grayscale, or with an alpha channel. Choosing the right display mode allows you to optimally use the downloaded data for further processing and image analysis.
- cv2.IMREAD_COLOR (default) — RGB color display.
- cv2.IMREAD_GRAYSCALE — grayscale display.
The cv2.imread function in the OpenCV library allows you to load images and is also used to desaturate color images. When loading a color image with cv2.imread, you can use a flag to convert it to grayscale. This is useful for image processing tasks such as edge detection or applying filters. Using cv2.cvtColor, you can easily convert an image to grayscale, simplifying further processing and analysis. Thus, cv2.imread is an essential tool for working with images in OpenCV, allowing you to effectively desaturate color photographs.

To save a new image in a separate file, use the cv2.imwrite function. This function from the OpenCV library allows you to save an image, creating a copy of it on your device. Simply specify the file name and path where you want to save the image, as well as the image array to be written. Make sure the file format meets the requirements to avoid errors when saving. Using cv2.imwrite is a simple and effective way to ensure that processed images are available for further use or analysis.
The function takes two arguments: the first is the name of the new file to save the image, and the second is a NumPy array containing the image data.
OpenCV provides the ability to work with image pixels through the use of NumPy arrays. This allows you to efficiently modify and process images, providing high flexibility in graphics manipulation. With this function, you can easily perform operations such as changing color saturation, contrast, and other image parameters.
First, you need to access a pixel. For this, we use coordinates. First, we specify the width coordinate, then the height coordinate. For example:
Let's change the color of a pixel to blue. To do this, you need to access the pixel by its coordinates and set its color to blue. Note that in this system, the colors blue and red are positioned relative to each other.
When you open the modified image, you will notice a black dot the size of one pixel in the upper right corner. This dot can be used to test the image quality or to verify its integrity. Pay attention to its location, as it can serve as an indicator of changes made to the file.
When manually replacing images, it is important to consider their dimensions. For this, we recommend using the image.shape function, which allows you to obtain the necessary image parameters. This information will help you properly adapt the images to your needs, ensuring optimal quality and format compliance. Using image.shape is a key step for efficient graphics processing.
- image.shape[0] — the image height in pixels.
- image.shape[1] — the image width in pixels.
Loops allow you to change the color of a large number of pixels at once. For example, you can create a 10-pixel black border around an image. This approach allows for efficient graphics management and improves image processing performance.
The outer loops iterate over each pixel in the image, starting with the horizontal (first loop) and moving to the vertical (second loop). The inner loops move from the edges of the image to its center, recoloring each pixel black at each step. This method allows for efficient image processing, ensuring full color resizing on each pass.
The result is the following image:

To resize the image, use the function cv2.resize. It can be used to reduce an image by half.
- image — the NumPy array of the image to be resized.
- (399, 368) — the width and height of the new image.
- cv2.INTER_AREA — the interpolation method, that is, the algorithm by which OpenVC chooses which colors to paint the pixels.
There are several interpolation methods, but in most cases it is sufficient to use only two of them: linear and polynomial interpolation. Linear interpolation allows you to create a simple model by connecting two known values, which makes it effective for quickly obtaining approximate data. Polynomial interpolation provides more accurate results, especially when there are more points to consider. These two interpolation methods are widely used in various fields, such as computer graphics, numerical methods, and data processing, making them indispensable tools for analysis and forecasting.
- cv2.INTER_LINEAR — for image enlargement. Used by default unless otherwise specified.
- cv2.INTER_AREA — for image reduction.
To preserve image proportions and eliminate the need to manually calculate them, it is recommended to use data obtained using the shape method. This method automatically determines the image dimensions, simplifying the process of processing and inserting it into web pages. Proper use of the shape method improves user experience and optimizes page loading, which is an important factor in SEO.
In both cases, the result remains the same:

To crop an image, you need to specify coordinate ranges that define the area you want to keep. First, specify the height, then the width. For example, if you want to keep a specific portion of the image, specify the corresponding crop values. This allows you to effectively manage the size and format of your images, improving the visual appeal of your content and optimizing it for the web. Proper image cropping also helps pages load faster and improve your site's SEO.

To rotate an image, use two functions at the same time. This allows you to change the orientation of an image with high precision and control. Using both functions provides flexibility in rotation settings, which is especially useful when working with graphic editors or web applications. Make sure you configure the parameters correctly to achieve the desired result in changing the image angle.
The cv2.getRotationMatrix2D function is used to create a rotation matrix, which is necessary for rotating an image. It accepts three main arguments: the rotation center, the rotation angle, and the scale. The rotation center specifies the point around which the rotation will occur, the angle specifies the degree of rotation in degrees, and the scale is responsible for changing the image size after rotation. Correct use of this function allows you to achieve high-quality and accurate image rotation in graphic applications.
- (399, 368) — coordinates of the point around which the rotation occurs.
- 60 — rotation angle in degrees.
- 0.8 — scaling factor. In our case, we scale the image down so that parts of the logo don't extend beyond the edge.
The cv2.warpAffine function in the OpenCV library is used to rotate and transform images. It accepts several arguments required to perform the operation. The main parameters are the source image, the transformation matrix, and the output image size. With this function, you can change the image orientation and apply other affine transformations, such as shearing and scaling. Correct use of cv2.warpAffine allows you to achieve high-quality results in image processing, making it an indispensable tool for developers working with computer vision and graphics.
- image — the image itself.
- matrix — the matrix created by the cv2.getRotationMatrix2D function.
- (image.shape[1], image.shape[0]) — the dimensions of the resulting image. In our case, we leave the same ones as before.

Script examples OpenCV
Let's create some simple image processing scripts using the OpenCV library in Python. OpenCV provides powerful tools for working with images, including loading, processing, and saving. In this tutorial, we'll cover the basic OpenCV functions that will help you get started with images, including resizing, applying filters, and converting to different color spaces. These simple scripts will help you quickly master the basics of working with images and use OpenCV's capabilities to solve a variety of problems.
OpenCV provides the ability to handle clicks on images displayed in the window. We'll implement functionality that allows you to output the coordinates of a point and its color code in BGR format to the terminal when you click on an image. This is useful for obtaining pixel information and analyzing color information in images.
In addition, we'll display information about the point that was clicked directly on the image. Left-clicking will display the coordinates, and right-clicking will display the BGR color code. This will allow the user to visually interact with the image and obtain the desired data instantly.
Create a click_event function that will handle click events on the image. This function should respond to clicks by performing the specified actions, such as changing the image style or opening a pop-up with additional information. Make sure the function is correctly bound to the image element and that it performs all the necessary actions to improve the user's interaction with the content.
The click_event function accepts five parameters that allow you to customize its operation. These parameters include: the click event, the ID of the element to attach the handler to, additional data that may be needed to handle the event, the callback function that will be executed when the event is triggered, and the context in which this function will be called. Properly configuring these arguments provides the flexibility and functionality of the click_event function, allowing developers to effectively manage user interactions with elements on a web page.
- event — the event that occurred (in our case, a mouse click).
- x and y — the coordinates of the clicked point.
- flags and params — utility arguments needed by the method we will use to call this function.
When any mouse button is clicked, the cursor coordinates and the BGR color code of the pixel at that point must be displayed in the terminal. To implement this task, use the appropriate mouse event handler. This handler should receive the cursor coordinates and then determine the pixel color based on these coordinates. As a result, both the coordinates and the BGR color code will be displayed in the terminal, allowing you to conveniently track color information at different points on the screen.
To implement a function that will display the coordinates of a point on an image when the left mouse button is pressed, you need to use JavaScript. An example of code that adds a click event handler to an image and draws a point at the specified position looks like this:
«`html
<!DOCTYPE html>
<html lang=»ru»>
<head>
<meta charset=»UTF-8″>
<meta name=»viewport» content=»width=device-width, initial-scale=1.0″>
<title>Coordinates of the point on the image</title>
<style>
#imageCanvas {
position: relative;
display: inline-block;
}
.dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
}
</style>
</head>
<body>
<div id=»imageCanvas»>
<img src=»path/to/your/image.jpg» alt=»Image» id=»image» />
</div>
<script>
const imageCanvas = document.getElementById(‘imageCanvas’);
imageCanvas.addEventListener(‘click’, function(event) {
const rect = imageCanvas.getBoundingClientRect();
const x = event.clientX — rect.left;
const y = event.clientY — rect.top;
const dot = document.createElement(‘div’);
dot.className = ‘dot’;
dot.style.left = `${x}px`;
dot.style.top = `${y}px`;
imageCanvas.appendChild(dot);
});
</script>
</body>
</html>
«`
In this code, we create a container for the image and add a mouse click event handler. When the image is clicked, the coordinates are calculated and a small red circle is created at that location, indicating the point. This code allows you to visualize the coordinates, which can be useful for various applications, such as image editors or interactive maps.
The cv2.putText function is an important tool for adding text to images in the OpenCV library. It accepts several arguments that allow you to customize the text display. The main arguments of the function include the image, text, starting point coordinates, font, font size, text color, and line thickness. Correct use of these parameters allows you to achieve high-quality text output, which is especially important for computer vision and image processing tasks. For example, with cv2.putText you can add annotations, labels, or any other text elements, making this function indispensable for data visualization.
- img is the image to which the caption is added.
- f'{x}, {y}’ — the caption that is added to the image.
- (x, y) — the coordinates of the point from which the caption originates.
- font — the caption font.
- 1 — text size scaling.
- (0, 0, 0) — text color.
- 2 — line thickness.
To implement the second condition, you need to supplement the code so that it displays the BGR code on the image when the right mouse button is pressed. Make sure that the event handler for the right mouse button responds correctly to user actions. When pressed, you need to get the cursor coordinates, convert them to BGR code, and display this code on the image. This will allow users to quickly and conveniently see the color they are pointing to, which will improve interaction with the application and increase its functionality.
The function is now ready for use. Now you need to transfer the image and use the built-in OpenCV function cv2.setMouseCallback. This method allows you to set up a mouse event handler, simplifying interaction with images and improving the user experience. It's important to set up the handler correctly to effectively handle clicks and mouse movements on the image.
Try testing the code. Open the image and right-click on each shape, then left-click on the space between them. As a result, you will get the expected result.

The following text is displayed in the terminal:
OpenCV offers advanced tools based on machine learning, One of which is the Haar model. This model effectively recognizes faces, making it useful for a variety of computer vision applications. Using Haar technology allows developers to create systems capable of identifying and tracking faces in real time, opening up new possibilities in areas such as security, medicine, and entertainment.
To use this feature, download the haarcascade_frontalface_default.xml file, which is available in the OpenCV repository on GitHub. This file is required for detecting faces in images and videos, making it an essential tool for developing computer vision applications.
To use this feature, you will need an image with human faces. In this example, we use a still from the movie "The Matrix", which was already mentioned at the beginning of the article.

Place these files in your script directory so you can access them by name. This will simplify working with resources and improve their usability in your project. Proper file structure organization is an important step for efficient development.
Import the OpenCV library and create variables for the Haar model and image. Use OpenCV to process images and recognize objects using cascaded Haar classifiers. Ensure that the paths to the model and image files are specified correctly to ensure the application functions correctly. Configure the classifier parameters according to your requirements for optimal object detection results.
When working with object recognition and comparison, desaturated versions of images are often used. Desaturated images highlight key characteristics of objects, making them easier to analyze. Let's desaturate our image for further processing and comparison.
To detect faces in an image, use the detectMultiScale method, which is based on the Haar model. This method effectively detects faces by analyzing various scales and image details, which allows for high recognition accuracy. Using Haar classifiers in combination with detectMultiScale makes the face detection process fast and reliable.
We pass the following parameters to the method:
- gray_image — desaturated image;
- scaleFactor=1.1 — image scaling step. The fact is that the model stores data on faces of a certain size. If the faces in the image are larger or smaller, the algorithm will not detect them. Therefore, during analysis, the image size is changed so that the faces in it at some point become the same size as in the model. The smaller the scaleFactor, the more accurate the recognition, but the slower it works;
- minNeighbors=5 — the minimum number of matches with the model required in the image to recognize an object as a face. The larger this argument, the fewer faces the algorithm will detect, but the chance of mistaking another object for a face decreases.
The detectMultiScale method returns the coordinates of detected objects, such as faces. To visualize these objects, you can use the cv2.rectangle function to outline the faces with squares. This will help you better understand which areas of the image have been recognized. Using these coordinates in combination with cv2.rectangle allows you to clearly demonstrate the results of the face recognition algorithm, providing a more efficient presentation of the data.
The faces variable contains an array consisting of four elements. Each element is a list that collects data from all detected objects.
- x — the horizontal coordinates of the object's upper-left corner.
- y — the vertical coordinates of the object's upper-left corner.
- w — the object's width.
- h — the object's height.
The cv2.rectangle function in the OpenCV library accepts several arguments that allow you to draw rectangles on images. The main parameters of this function include the image, the coordinates of the rectangle's upper-left and lower-right corners, the color, and the line thickness. The image is specified in array format, and the coordinates are defined in pixels. The color is specified in BGR format, which is the OpenCV standard. The line thickness indicates how pronounced the rectangle's border will be. Thus, cv2.rectangle provides a flexible tool for image annotation in computer vision, which can be useful in various tasks such as image processing and visualization.
- image is the color image on which we draw the square.
- (x, y) are the coordinates of the upper-left corner of the square.
- (x+w, y+h) are the coordinates of the lower-right corner of the square.
- (0, 0, 255) is the color of the square in BGR format.
- 2 is the line thickness of the square in pixels.
Let's analyze the resulting image.

It worked: the faces in the reflection are outlined in frames. This effect adds depth and emphasizes details, creating a unique visual perception. Frames emphasize the individuality of each image and make it more memorable. Using such techniques in design helps highlight key elements and create a harmonious blend with the surrounding space.
What's Next
For a deeper understanding of computer vision and OpenCV, we recommend familiarizing yourself with a number of additional resources and materials. Studying the theoretical foundations and practical examples will help you better master this area. Pay attention to online courses, video tutorials, and specialized books that cover both basic and advanced aspects of working with OpenCV. It is also useful to participate in forums and communities where the latest achievements and applications of computer vision are discussed. This will not only expand your knowledge but also receive support from professionals in this field.
- tutorials from the OpenCV documentation (English);
- OpenCV Python Tutorial from the GeeksforGeeks platform (English);
- Aniradh Cole, Meher Kazam, Siddha Ganju. "Artificial Intelligence and Computer Vision";
- Eduard Shakiryanov. "Computer Vision in Python";
- OpenCV Course — Full Tutorial with Python (video, English subtitles available).
Explore additional materials:
- Artificial Intelligence, Machine Learning, and Deep Learning: What's the Difference?
- "I Completed the Course Module and Started Sending Out CVs": A Musician Who Became a Pythonista
- Creating "Snake" — the First Game in Python and Pygame
Learn more about coding and related topics in our Telegram channel. Subscribe to stay up to date with important updates and interesting content!

