Image Processing — OpenCV Vs PIL. Utilize the Python Libraries to Extract... | by Suraj Gurav | Towards Data Science

The work of a Data Analyst is not limited to work only on readily available data, rather sometimes the data need to be mined from the images also.
This story is all about different types of image feature extraction using Python. Additionally, here you will find a classic comparison of the speed of two image processing libraries — OpenCV and PIL
____ OpenCV is 1.4 Times faster than PIL ____
📌 Want to follow along? here is my Jupyter-Notebook.📌 More resources are always mentioned with 💡
In my recent project, I need to process 10000+ images per day and extract the data from them. And only Python can help me with this batch processing. I usually do the below processes on image:1. Extract the aspect ratio of the image.2. Crop the image.3. Change the image to grayscaled one.4. Image Rotation.However, my work doesn’t stop here. I do much more ad-hoc analysis.
In my project, a lot of information is also hidden in the image name. And the string manipulation methods discussed here are quite handy in such tasks.
towardsdatascience.com
Image is simply a matrix of pixels and each pixel is the single, square-shaped point of colored light. This can be explained quickly with a grayscaled image. grayscaled image is the image where each pixel represents different shades of a gray color.
In the picture above, the original image on the left side is actually the distribution of different shades of a gray color. On the right side, in the array of pixel gray values, the value 0 represents the black color and the value 255 represents the white color. All the values between 0 and 255 represent different shades of a gray color. Further information about this can be found here.
A random google search 🔍 for image processing in Python points towards these frequently used image processing libraries.
OpenCV is written in C and C++ whereas PIL is written using Python and C, hence just from this information, OpenCV seems faster. While dealing with 1000s of images for data extraction, the processing speed 🚀 matters.Here is a quick comparison of these two libraries.
I mostly use OpenCV to complete my tasks as I find it 1.4 times quicker than PIL. First, let me show you step by step, how the image can be processed using both — OpenCV and PIL.
First of all, install the OpenCV Python package and import the package into Jupyter-Notebook or Python IDE.
pip install opencv-pythonimport cv2
Installation needed only for the 1st time usage.
img = cv2.imread(path_to_the_image)Use this method from the OpenCV package to read the image into a variable img. As I mentioned earlier, OpenCV reads the image in BGR format by default.
What are BGR and RGB formats?Both stand for the same colors (R) Red, (G) Green, (B) Blue but the order of arranging these colors areas is different. In BGR, the red color channel is considered as least important and in RGB, the blue color channel is the least important.
For the sake of this article, I will convert it to RGB format using the cvtColor method.
Let’s crop the image keeping the aspect ratio the same. So the area with the same aspect ratio will be cropped from the center of the image.
The aspect ratio of an image is the ratio of its width to its height. It is commonly expressed as two numbers separated by a colon, as in width:height. for example, 16:9.
In OpenCV, the image is a NumPy array and crops the image in the same way as NumPy array slicing. That’s why it is 8210X faster than PIL.
Image rotation is quite straightforward here. The method rotate() in OpenCV allows image rotation in the multiples of 90°.
💡 More info about the method rotate() can be found here.
“Grayscale” image is an image that is composed of different shades of gray only, varying from black to white. An 8-bit image has 256 different shades of Gray color. Meaning, each pixel of the image, takes a value between 0 and 255. Again using the method cvtColor() to convert the rotated image to the grayscale.
💡 All the color conversion codes can be found here.
Pillow is the currently used library, which is derived from PIL.For the first-time usage, start with package installation. And then import the package into Jupyter-Notebook or Python IDE.
pip install Pillowfrom PIL import Image, ImageEnhance
Imported Image module has the method open() which comes in handy while reading the image in PIL. Just like OpenCV, the image name with the extension or the entire path can be passed to this method.
The same class Image has the method crop() to crop the image. The image cropping with PIL is slightly different than OpenCV.
Image.crop() takes a tuple as input. This tuple includes the coordinates for the upper left and the lower right corner of the area to be cropped.
Image class includes also the method rotate(). And unlike OpenCV, only the anticlockwise rotation angle as an integer can be passed to this method.
Just like the other tasks in PIL, the image format conversion is also straightforward. The method convert() returns the converted image.
Well, the programmatical way of image data mining is commonly used for batch image processing. And there comes the game of speeds ⏳.
I downloaded 880 images 🎁 from google and processed each image 10 times to have enough load on the program, to find out the time required for the image processing in OpenCV and in PIL.
As expected, the time taken by OpenCV was less as compared to PIL i.e. OpenCV was faster than PIL.
💡 Theoretical explanation about how image processing is done in OpenCV can be found here. The beauty of OpenCV is, you can see numerous examples on its website in Python, C++, and Java.
Similarly, more info about PIL can be gathered here. 💡
This was just an overview of the two most frequently used Python packages for image processing and how they work differently to return the same results. I hope you enjoyed and learned something from this read.
Typically for my work, I found OpenCV more reliable and faster, however, the inverse is also possible depending on different image processes.
As I always say, I am open to constructive feedback and knowledge sharing through LinkedIn.
📚 Have a look at my other articles about Data Analytics here.
Visualize SQLite Data with Power BILabel Encoder and OneHot Encoder in PythonSQL Database with PythonWeb Scraping — Make your Own DatasetHypothesis Testing & p-ValueJoin the Tables
Visualize SQLite Data with Power BI
Label Encoder and OneHot Encoder in Python
SQL Database with Python
Web Scraping — Make your Own Dataset
Hypothesis Testing & p-Value
Join the Tables
Become a Medium member today & get ⚡ unlimited ⚡ access to all the Medium stories.
Sign up here and Join my email subscriptions
When you sign-up here and choose to become a paid medium member, I will get a portion of your membership fee as a reward.