<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Saksham Sinha on Medium]]></title>
        <description><![CDATA[Stories by Saksham Sinha on Medium]]></description>
        <link>https://medium.com/@saksham.sinha?source=rss-457ed7ab0cb4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ji6L87zzD3MWnTU2X5RcDA.jpeg</url>
            <title>Stories by Saksham Sinha on Medium</title>
            <link>https://medium.com/@saksham.sinha?source=rss-457ed7ab0cb4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:22:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saksham.sinha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Image read and resize with OpenCV, Tensorflow and PIL.]]></title>
            <link>https://medium.com/data-science/image-read-and-resize-with-opencv-tensorflow-and-pil-3e0f29b992be?source=rss-457ed7ab0cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e0f29b992be</guid>
            <category><![CDATA[pillow]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[resize-images]]></category>
            <category><![CDATA[opencv-python]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <dc:creator><![CDATA[Saksham Sinha]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 10:06:21 GMT</pubDate>
            <atom:updated>2020-04-24T12:42:18.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>Switching among OpenCV, Tensorflow and Pillow? Wait!!!</h3><h4>A dive into the differences in JPEG image read and resizing with OpenCV, Tensorflow and Pillow and also on how to make them consistent.</h4><p>Modern Computer Vision (CV) is currently a hot field of research which involves largely working with images. For this, one needs to use a framework to open those images to do some processing on them.</p><p>In today’s rapid development of frameworks, every framework has its own way of handling images, each with its own specifications. Therefore, CV solutions developed in one framework may not work as expected in the other framework. The blog “How Tensorflow’s tf.image.resize stole 60 days of my life” (<a href="https://hackernoon.com/how-tensorflows-tf-image-resize-stole-60-days-of-my-life-aba5eb093f35">https://hackernoon.com/how-tensorflows-tf-image-resize-stole-60-days-of-my-life-aba5eb093f35</a>) is a perfect example of this type of situation. It can take up multiple days to figure out what went wrong and could delay the project extensively.</p><p>This blog will discuss one such use case in detail where OpenCV and Tensorflow show the differences in reading and resizing a JPEG image. It will also show a way to make them work consistently. Also, thanks to <a href="https://medium.com/u/59b036ba6f25">Tejas Pandey</a> for the help in achieving consistency between OpenCV and Tensorflow.</p><h4>Please note that I am an employee of Intel and all information and opinions shown in the blog are my own and don’t represent those of my employer.</h4><p>We’ll start with opening a simple JPEG image of a dog with two frameworks Tensorflow 1.x and OpenCV.</p><p>Let’s get started. We’ll import a few essential libraries in python.</p><pre>%tensorflow_version 1.x<br>import cv2<br>import matplotlib.pyplot as plt<br>import numpy as np<br>from skimage import io<br>import tensorflow as tf</pre><p>Let’s open an image using OpenCV.</p><pre>image_path = &#39;dog2.JPG&#39;</pre><pre>def plt_display(image, title):<br>  fig = plt.figure()<br>  a = fig.add_subplot(1, 1, 1)<br>  imgplot = plt.imshow(image)<br>  a.set_title(title)</pre><pre>image = cv2.imread(image_path)<br>plt_display(image, &#39;cv2-BGR&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*GRMR9CCHR5MV1dgpW7XNvA.png" /></figure><p>Something’s strange about this figure above. It doesn’t look like the original. Well, yes, that’s true. Before diving into this, first let’s learn how colors in images are represented. Generally, images have three colors channels Red, Green, and Blue (RGB) which produces the colors in the pixel. The order of these channels changes the color of the pixels, as pixels will always interpret first channel as Red, second channel as Green and third channel as Blue.</p><p>Now that we have an understanding of how color channels work in an image, let’s look into why we saw a different color image above. When we open an image using OpenCV, by default OpenCV opens the image in Blue, Green and Red channel (BGR). This is fine but when we display the image, the pixels misinterpret the channels (i.e. pixels get confused and interpret Blue as Red and vice-versa). That’s why we get the above wrong colors in the image.</p><p>So how to fix this? After opening the image, we convert the image from BGR to RGB. We do this by using the OpenCV flag COLOR_BGR2RGB. The code below shows how to open an image with OpenCV correctly.</p><pre>image_cv = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br>print(image_cv.dtype)<br>print(np.max(image_cv))<br>plt_display(image_cv, &#39;cv2-RGB&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*Wah_X1YEp9yq6u-xrbCT6Q.png" /></figure><p>Let’s open an image with Tensorflow now and see if we get the same results. It’s a two-step process to open a JPEG image in Tensorflow. The first step is to open the image, and the second step is to perform JPEG decoding as JPEG is a compressed image.</p><pre>print(&quot;Tensorflow version: &quot;, tf.__version__)<br>image_tf = tf.io.read_file(image_path)</pre><pre>image_tf = tf.image.decode_jpeg(image_tf, channels=3)</pre><pre>with tf.Session() as sess:<br>    image_tf = image_tf.eval()</pre><pre>print(image_tf.dtype)<br>plt_display(image_tf, &#39;TF&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*lxkqmo9BjUaorKNf1c8dqg.png" /></figure><p>On visual inspection, the image read from OpenCV and Tensorflow look the same. But are they? To see what are the differences, let’s subtract the two. If the two are same, we should see a completely black image. If not, then we will see some pixels with different colors.</p><pre>image_diff = np.abs(image_cv- image_tf)<br>plt_display(image_diff, &#39;OpenCV-TF&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*mFk2nqTg7ijmZjw9OQ5qPw.png" /></figure><p>Woah! That’s a huge difference. What went wrong? Well, this difference is arising from the fact that OpenCV, by default, uses integer accurate decompression of the JPEG image. In contrast, TensorFlow uses Discrete Cosine Transform as default. This type of decoding is inaccurate and so to make it the same as OpenCV, we need to decode it by using integer accurate decompression. This can be done by setting the parameter dct_method=’INTEGER_ACCURATE’ as shown below.</p><pre>image_tf = tf.io.read_file(image_path)</pre><pre>image_tf = tf.image.decode_jpeg(image_tf, channels=3, dct_method=&#39;INTEGER_ACCURATE&#39;)</pre><pre>with tf.Session() as sess:<br>    image_tf = image_tf.eval()</pre><pre>plt_display(image_tf,&#39;TF_INT_ACC&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*7JtnrSqJ55YO84xONFfA-w.png" /></figure><p>And now subtracting with the OpenCV image we get a black image. This means both our TF and OpenCV are now consistent in reading the image. This is an essential step because a small change in how you read the image will give rise to significant differences in the processing of the image later.</p><pre>image_diff = np.abs(image_cv- image_tf)<br>plt_display(image_diff, &#39;OpenCV-TF&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*E6Fgg23wa0L9z87qX57HUw.png" /></figure><p>Now, since we have read the image consistently with OpenCV and TensorFlow, let’s try the resizing of the images with these frameworks. We’ll begin with OpenCV resize first.</p><pre># resizing the image with OpenCV<br>print(&quot;image shape before resize:&quot;, image_cv.shape)<br>image_cv_resized = cv2.resize(image_cv,(300,300))<br>print(&quot;image shape after resize:&quot;, image_cv_resized.shape)<br>print(&quot;image dtype: &quot;, image_cv_resized.dtype)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*nG3cufoz1nKY7nZm6xT13w.png" /></figure><p>We have the OpenCV resize done. Now let’s do the TensorFlow resize. Tensorflow work with tensors. It’s resizing method expects a 4D tensor and returns a 4D tensor output. Hence, we will have to first expand the image from three to four. Then resize the image and squeeze the dimensions back to three. Since our image is still a tensor, we will create and run a Tensorflow session to get back our resized image in NumPy format. Once we have the NumPy image, we convert it to uint8 type as by default, session converts the NumPy to float32 type. This makes the types inconsistent with OpenCV. This is shown below-</p><pre># resizing the image with tensorflow 1.x<br>print(&quot;image shape before resize:&quot;, image_tf.shape)<br>print(&quot;image dtype: &quot;, image_tf.dtype)</pre><pre>#This function takes in a 4D input. Hence we will have to expand the image and then squeeze back to three dimensions before we can use it as an image.<br>image_tf_4D= tf.expand_dims(image_tf,0)</pre><pre># doing bilinear resize<br>image_tf_resized_4D = tf.image.resize_bilinear(<br>    image_tf_4D,<br>    (300,300)<br>)</pre><pre>#squeezing back the image to 3D<br>image_tf_resized = tf.squeeze(image_tf_resized_4D)</pre><pre>#Above is still a tensor. So we need to convert it to numpy. We do this by using tf session.<br>with tf.Session() as sess:<br>  image_tf_resized = image_tf_resized.eval()</pre><pre>print(&quot;image shape after resize:&quot;, image_tf_resized.shape)<br>print(&quot;image dtype: &quot;, image_tf_resized.dtype)</pre><pre>#Since it is in float32 format, we need to convert it back to uint8.<br>image_tf_resized = image_tf_resized.astype(np.uint8)<br>print(&quot;image dtype after conversion uint8: &quot;, image_tf_resized.dtype)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*tK_BSQAZR0WkK1FODd1enw.png" /></figure><p>Now let’s see the difference between the resized images from OpenCV and TF.</p><pre>image_resized_diff = np.abs(image_cv_resized- image_tf_resized)<br>plt_display(image_resized_diff, &#39;Resized OpenCV2 - Resized TF&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*wvAd5QvCt92BNTdGFELKkQ.png" /></figure><p>We again see a big difference in the resize method of the two frameworks. Even when we opened the images consistently across both frameworks, the resize method gave different results. OpenCV resize method, by default, uses bilinear transformation. We used the same bilinear method with Tensorflow. Still, we ended up with different results.</p><p>This happened because OpenCV adds half-pixel corrections to the image while resizing. Whereas Tensorflow by default doesn’t. This adds up the difference in the resizing method outputs.</p><p>In order to fix this problem, there is a parameter in the TensorFlow bilinear resize that will do the half-pixel correction. This is shown below-</p><pre>image_tf_4D= tf.expand_dims(image_tf,0)</pre><pre># doing bilinear resize with half pixel correction<br>image_tf_resized_hpc_4D = tf.image.resize_bilinear(<br>    image_tf_4D,<br>    (300,300),<br>    half_pixel_centers=True<br>)</pre><pre>image_tf_resized_hpc = tf.squeeze(image_tf_resized_hpc_4D)</pre><pre>with tf.Session() as sess:<br>  image_tf_resized_hpc = image_tf_resized_hpc.eval()</pre><pre>image_tf_resized_hpc = image_tf_resized_hpc.astype(np.uint8)<br>image_resized_diff = np.abs(image_cv_resized- image_tf_resized_hpc)<br>plt_display(image_resized_diff, &#39;Resized OpenCV2 - Resized TF&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*VX5qH_l9oXF4-V_7t2yhcg.png" /></figure><p>And now we have the expected result. Finally, we have Tensorflow and OpenCV working consistently with reading and resizing images.</p><p>A new person in the Computer Vision field trying out these functions will more likely make these mistakes and will be off to a bad start. Tutorials across the internet do not discuss this in detail. I created this blog to show people that from one framework to another, small minor things like what I discussed need to be checked and kept consistent. Otherwise, they will have different results in different frameworks and will adversely affect their work.</p><p>Another framework widely used is Pillow (PIL). Let’s see the differences with PIL and OpenCV. We’ll first read the image using PIL.</p><pre>from PIL import Image</pre><pre>orig_image_pil = Image.open(image_path)<br>image_pil = np.asarray(orig_image_pil)<br>print(image_pil.dtype)<br>plt_display(image_pil, &#39;PIL&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*9JKi1TuVId0RdrayphaRNQ.png" /></figure><p>Now we will see if there is any difference between JPEG image opened by PIL and OpenCV.</p><pre>image_cv_pil_diff = np.abs(image_cv - image_pil)<br>plt_display(image_cv_pil_diff, &#39;CV-PIL-DIFF&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*rJ-biQ_5qTYqCW2OKsS9Yw.png" /></figure><p>As expected from our experience from TF and OpenCV, these two frameworks again open the images differently. PIL, by default, doesn’t provide any way to use integer accurate decompression. However, one can write their own decoder to decode images. But in this blog, I am only showing the differences and if possible, to make them consistent if the library provides the support for it.</p><p>Since the images are read differently between these frameworks, this difference will propagate when we do resize. This is shown below-</p><pre>image_pil_resized = orig_image_pil.resize((300,300),       resample=Image.BILINEAR)<br>image_pil_resized = np.asarray(image_pil_resized)</pre><pre>#making sure we have the same dtype as OpenCV image.<br>print(image_pil_resized.dtype)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/80/1*ecA7FYj8gW5zM3wQlbFycw.png" /></figure><pre>image_cv_pil_resize_diff = np.abs(image_cv_resized - image_pil_resized)<br>plt_display(image_cv_pil_resize_diff, &#39;Resized CV- Resized PIL&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*3_VfcjzL76e1CJk0szeaIQ.png" /></figure><p>Hence, we get the expected difference in resizing. PIL library doesn’t provide any support for half-pixel correction, and so there is no by default support for this. Since we know TF and OpenCV are consistent, we can expect the same results when considering the difference between PIL and TF as well.</p><p>Hence, when using PIL framework, one must keep this in mind that one cannot switch directly to another framework if the work is dependent on the pre-processing of the images such as above. This will lead to unexpected results.</p><p>I hope that this blog was useful to you and was able to make you aware of the framework dependent processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e0f29b992be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/image-read-and-resize-with-opencv-tensorflow-and-pil-3e0f29b992be">Image read and resize with OpenCV, Tensorflow and PIL.</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>