<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>emre şahin's digital garden 🍃 - NumPy</title>
    <link>https://emresahin.net/tags/numpy/</link>
    <description>Posts in the NumPy tag</description>
    <language>en</language>
    <managingEditor>contact@emresahin.net (Emre Şahin)</managingEditor>
    <lastBuildDate>Tue, 15 Sep 2026 19:46:32 +0000</lastBuildDate>
    <atom:link href="https://emresahin.net/tags/numpy/rss.xml" rel="self" type="application/rss+xml"/>
    <item>
      <title>Converting MNIST and Fashion-MNIST IDX format to NumPy</title>
      <published>2021-07-01T20:46:12+00:00</published>
      <updated>2021-07-01T20:46:12+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Thu, 01 Jul 2021 20:46:12 +0000</pubDate>
      <link>https://emresahin.net/convert-mnist-data-to-numpy/</link>
      <guid isPermaLink="true">https://emresahin.net/convert-mnist-data-to-numpy/</guid>
      <description>MNIST and the newer Fashion-MNIST datasets are among the most well-known datasets for testing Machine Learning models. Although the original MNIST dataset is considered solved, it will likely remain a staple for a long time. These datasets are provided in a binary format. There are four files—two...</description>
      <category>Python</category>
      <category>Machine Learning</category>
      <category>MNIST</category>
      <category>Fashion-MNIST</category>
      <category>IDX</category>
      <category>IDX3</category>
      <category>NumPy</category>
      <content:encoded><![CDATA[<p>MNIST and the newer Fashion-MNIST datasets are among the most well-known datasets for testing Machine Learning models. Although the original MNIST dataset is considered solved, it will likely remain a staple for a long time.</p>
<p>These datasets are provided in a binary format. There are four files—two for the training set and two for the test set—in gzipped <code>IDX</code> and <code>IDX3</code> formats. Although it is a simple format, it is non-standard and requires custom code to parse.</p>
<p>For a professional project, I wrote the following two functions to load these files into NumPy arrays.</p>
<pre><code class="language-python">
import struct
import gzip
import numpy as np

def mnist_images_idx_to_array(images_filename):
    images_f = gzip.open(images_filename, mode="rb")
    images_f.seek(0)
    magic = struct.unpack('&gt;I', images_f.read(4))[0]
    if magic != 0x00000803:
        raise Exception(f"Format error: Need an IDX3 file: {images_filename}")
    n_images = struct.unpack('&gt;I', images_f.read(4))[0]
    n_row = struct.unpack('&gt;I', images_f.read(4))[0]
    n_col = struct.unpack('&gt;I', images_f.read(4))[0]

    n_bytes = n_images * n_row * n_col  # each pixel is 1 byte

    images_data = struct.unpack(
        '&gt;' + str(n_bytes) + 'B', images_f.read(n_bytes))

    images_array = np.asarray(images_data, dtype='uint8')
    images_array.shape = (n_images, n_row, n_col)

    return images_array


def mnist_labels_idx_to_array(labels_filename):
    labels_f = gzip.open(labels_filename, mode="rb")
    labels_f.seek(0)
    magic = struct.unpack('&gt;I', labels_f.read(4))[0]
    if magic != 0x00000801:
        raise Exception(f"Format error: Need an IDX file: {labels_filename}")
    n_labels = struct.unpack('&gt;I', labels_f.read(4))[0]
    labels_data = struct.unpack(
        '&gt;' + str(n_labels) + 'B', labels_f.read(n_labels))
    labels_array = np.asarray(labels_data, dtype='uint8')
    return labels_array


</code></pre>
<p>You can use these functions by passing the appropriate filenames, as shown below:</p>
<pre><code class="language-python">

training_images = mnist_images_idx_to_array(
    os.path.join(input_dir, "train-images-idx3-ubyte.gz"))
training_labels = mnist_labels_idx_to_array(
    os.path.join(input_dir, "train-labels-idx1-ubyte.gz"))
testing_images = mnist_images_idx_to_array(
    os.path.join(input_dir, "t10k-images-idx3-ubyte.gz"))
testing_labels = mnist_labels_idx_to_array(
    os.path.join(input_dir, "t10k-labels-idx1-ubyte.gz"))

</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>How to convert NumPy image to QImage?</title>
      <published>2018-11-06T20:11:46+00:00</published>
      <updated>2018-11-06T20:11:46+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Tue, 06 Nov 2018 20:11:46 +0000</pubDate>
      <link>https://emresahin.net/converting-numpy-image-to-qimage-14359-22392/</link>
      <guid isPermaLink="true">https://emresahin.net/converting-numpy-image-to-qimage-14359-22392/</guid>
      <description>When writing Qt GUI code for a deep learning system, a common task is converting an image (read from disk or camera using OpenCV) from a NumPy array to a QImage for display in a widget. There are basically two problems to address: NumPy arrays often have data types with more than 8 bits, and Open...</description>
      <category>Python</category>
      <category>Qt</category>
      <category>NumPy</category>
      <category>QImage</category>
      <category>PySide2</category>
      <category>OpenCV</category>
      <category>Image Processing</category>
      <content:encoded><![CDATA[<p>When writing Qt GUI code for a deep learning system, a common task is converting an image (read from disk or camera using OpenCV) from a NumPy array to a QImage for display in a widget.</p>
<p>There are basically two problems to address: NumPy arrays often have data types with more than 8 bits, and OpenCV reads images in BGR format rather than the more common RGB.</p>
<p>The following Python (3.5+) code demonstrates the solution:</p>
<pre><code class="language-python">import PySide2.QtGui as qtg
import numpy as np

def get_qimage(image: np.ndarray):
    assert (np.max(image) &lt;= 255)
    image8 = image.astype(np.uint8, order='C', casting='unsafe')
    height, width, colors = image8.shape
    bytesPerLine = 3 * width

    image = qtg.QImage(image8.data, width, height, bytesPerLine,
                       qtg.QImage.Format_RGB888)

    image = image.rgbSwapped()
    return image
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Numpy ValueError while using dlib's face detector</title>
      <published>2018-10-24T21:41:18+00:00</published>
      <updated>2018-10-24T21:41:18+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Wed, 24 Oct 2018 21:41:18 +0000</pubDate>
      <link>https://emresahin.net/value-error-dlib-14346-27722/</link>
      <guid isPermaLink="true">https://emresahin.net/value-error-dlib-14346-27722/</guid>
      <description>For two days, I was trying to find a bug in my code because an assertion in the code that uses numpy.max was throwing an error: ValueError: zero-size array to reduction operation maximum which has no identity , which didn’t seem reasonable. I’m building a face recognizer with dlib ’s frontal face...</description>
      <category>Machine Learning</category>
      <category>Python</category>
      <category>Debugging</category>
      <category>dlib</category>
      <category>NumPy</category>
      <category>Face Detection</category>
      <category>Python</category>
      <category>Computer Vision</category>
      <category>ValueError</category>
      <content:encoded><![CDATA[<p>For two days, I was trying to find a bug in my code because an assertion in the
code that uses <code>numpy.max</code> was throwing an error: <code>ValueError: zero-size array to reduction operation maximum which has no identity</code>, which didn’t seem
reasonable.</p>
<p>I’m building a face recognizer with <a href="https://github.com/davisking/dlib/">dlib</a>’s
frontal face detector, and today, I noticed that some of the results return
<em>negative</em> coordinates in face detection. This means the detected face is
partial, although it’s a bit of a stretch to use negative coordinates for this.</p>
<p>My code wasn’t checking for negative coordinates and was building the NumPy
array incorrectly. However, after reading <a href="https://github.com/davisking/dlib/issues/767">the
issue</a>, although I’m still not convinced
that it’s a good approach, I added a few <code>if</code> statements and the problem was solved.</p>]]></content:encoded>
    </item>
  </channel>
</rss>
