<?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 Steven Yeung on Medium]]></title>
        <description><![CDATA[Stories by Steven Yeung on Medium]]></description>
        <link>https://medium.com/@steven.yeung?source=rss-acf6fbed038f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6uNiHAxMLnjJxrhZ</url>
            <title>Stories by Steven Yeung on Medium</title>
            <link>https://medium.com/@steven.yeung?source=rss-acf6fbed038f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:10:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@steven.yeung/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[Pipeline to process and OCR historical news archive]]></title>
            <link>https://medium.com/scmp-inside-the-wonton/pipeline-to-process-and-ocr-historical-news-archive-8712f8743561?source=rss-acf6fbed038f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8712f8743561</guid>
            <category><![CDATA[newspapers]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Steven Yeung]]></dc:creator>
            <pubDate>Tue, 15 Dec 2020 11:59:15 GMT</pubDate>
            <atom:updated>2020-12-18T02:14:30.044Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a follow-up article to the previous blog post: <a href="https://medium.com/scmp-inside-the-wonton/using-ai-to-denoise-scanned-newspaper-88f4e34f59c0">Using AI to denoise scanned newspapers</a>.</p><h3>TL;DR</h3><p>The idea of using Denoising Autoencoder (DAE) to denoise scanned newspaper has proven to be very successful. In order to further improve the OCR accuracy, we have employed traditional image processing into the pipeline to further remove unwanted elements in the image, e.g. borders and graphics.</p><p>The following image shows the original scanned copy versus the end result of the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oXoepnVgAQRU0_pwotC-TA.jpeg" /><figcaption>Figure 1. Original image (left) and final result (right) processed by the pipeline.</figcaption></figure><p>We will go through each step of the pipeline, and see how we gradually improve the image for OCR.</p><p>The main components of the pipeline include:</p><ul><li>upload: The stage where we parse the segmented data from XML to JSON, and upload source files to a central repository for processing in the later stages.</li><li>prep: Using traditional image processing to remove borders and graphics.</li><li>ocr: Using DAE AI model to denoise and perform OCR by Tesseract.</li></ul><p>Because we have over 100 years of news archive to process, the pipeline will use Celery to manage the task queue, and Kubernetes to run the tasks in scale.</p><h3>API and Storage</h3><p>The OCR text and PDFs will eventually be migrated into our in-house archiving system: “Nexus”. In order for Nexus to access and other pipeline components to upload the artifacts, we need a central repository: The API.</p><p>The API is based on <a href="https://fastapi.tiangolo.com/">FastAPI</a>, with MongoDB as a database and AliCloud Object Storage Service (<a href="https://www.alibabacloud.com/product/oss">OSS</a>) as file storage. We use API to generate signed URL to directly manage files on OSS, and API itself doesn’t have to handle file upload and download, which allows the API to scale smoothly by Kubernetes Horizontal Pod Autoscaler (HPA).</p><p>FastAPI is very easy to use and build. Because it is based on OpenAPI, it automatically generates the JSON schema on the fly, and developers can browse the API endpoints using Swagger UI. FastAPI is very fast and below is a simple benchmark against a listing of OCR records.</p><pre>siege -c10 -r100 https://example.com/scmp-ocrs/?model=s152-2020-11-09.h5&amp;year=1980&amp;limit=20<br>{<br>  &quot;transactions&quot;: 1000,<br>  &quot;availability&quot;: 100,<br>  &quot;elapsed_time&quot;: 6.06,<br>  &quot;data_transferred&quot;: 18.45,<br>  &quot;response_time&quot;: 0.06,<br>  &quot;transaction_rate&quot;: 165.02,<br>  &quot;throughput&quot;: 3.04,<br>  &quot;concurrency&quot;: 9.11,<br>  &quot;successful_transactions&quot;: 1000,<br>  &quot;failed_transactions&quot;: 0,<br>  &quot;longest_transaction&quot;: 0.35,<br>  &quot;shortest_transaction&quot;: 0.02<br>}</pre><p>During the pipeline development, we also found a useful project: <a href="https://openapi-generator.tech/">OpenAPI Generator</a>. It takes the OpenAPI schema, and generate the SDK of your preferred programming language. We used the generated SDK to write the pipeline components and everything works without any problem.</p><h3>Task: “upload”</h3><p>We had two vendors to help with the historical archives. One of them helped to scan microfilms and newspapers into TIFF image format. The other vendor helped to segment the pages into articles. Metadata are saved in XML format, articles are stored in PDF, and graphics found inside articles are stored in JPG format.</p><p>Because these two repositories are only available within the company network through SMB, I have to upload the following data to the API from my workstation:</p><ul><li>Upload scanned TIFF images to OSS.</li><li>Parse article XML to JSON and store in API.</li><li>Upload article PDF and graphic JPG files to OSS.</li></ul><p>This is the only step that can not be scaled, but luckily it only has to be performed once.</p><h3>Task: “prep”</h3><h3>Getting the article from the scanned TIFF image</h3><p>At the beginning of this project, the idea is to desnoise the article PDF image and run the OCR again. But we noticed there are some character details lost in the article PDF when compared to the scanned page TIFF. The image below shows that the characters lost details in the PDF image, while the text in the TIFF image is still clear to read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*kE9OKuBE-mlM6bs4RUEfYg.jpeg" /><figcaption>Figure 2. The PDF image from OCR vendor (left) and image from scanned TIFF (right).</figcaption></figure><p>In this case, we have to use the article PDF as a clue and find the corresponding article on the page TIFF. We use the OpenCV ORB algorithm to perform feature extraction, and then use FLANN to find the best matches between the two images. After getting the matches, we are able to find the homography of the two images, and get the article from the scanned page TIFF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*3fOucLk19ugyPRC4Am6h-g.jpeg" /><figcaption>Figure 3. The green lines show the matching features.</figcaption></figure><p>Detailed tutorial please refer to OpenCV <a href="https://docs.opencv.org/4.5.0/dc/dc3/tutorial_py_matcher.html">official documentation</a>.</p><h3>Removing graphics</h3><p>If we apply DAE on articles with graphics, the graphics tend to be “washed”. It blurs or erases part of the graphics, and Tesseract may try to perform OCR on them. This will produce a lot of meaningless text. Therefore, we use the same technique as above. Take the graphics JPG image as a clue to find their location in the article and remove them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*E3pRIFKGFtEJYHu8oBDTfw.jpeg" /><figcaption>Figure 4. The green lines show the matching features of both images.</figcaption></figure><p>At this stage, we can get the article from the scanned TIFF image and remove all graphical elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*aP9fnnUWB4xdYtw2ndD_vw.jpeg" /><figcaption>Figure 5. Before (left) and after (right) graphic removal.</figcaption></figure><h3>Removing borders</h3><p>According to Tesseract <a href="https://tesseract-ocr.github.io/tessdoc/ImproveQuality.html#Borders">best practices</a>, we need to remove the borders to improve accuracy. So the next step in the pipeline is to find all vertical and horizontal lines in the article image.</p><p>A common technique is to use erode and dilate to find all horizontal lines (100x1) and vertical lines (1x100), and subtract the lines with the original image in order to remove them.</p><pre>def del_lines(img: np.ndarray, horizontal: int, vertical: int, enlarge: int = 0):<br>    # Invert the image.<br>    img = cv2.bitwise_not(img)</pre><pre>    # Get all horizontal lines.<br>    horizontal_structure = cv2.getStructuringElement(cv2.MORPH_RECT, (horizontal, 1))<br>    img_horizontal = cv2.erode(img, horizontal_structure)<br>    img_horizontal = cv2.dilate(img_horizontal, horizontal_structure)</pre><pre>    # Get all vertical lines.<br>    vertical_structure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, vertical))<br>    img_vertical = cv2.erode(img, vertical_structure)<br>    img_vertical = cv2.dilate(img_vertical, vertical_structure)</pre><pre>    # Combine the two images.<br>    img_combined = cv2.add(img_horizontal, img_vertical)</pre><pre>    # Make the lines thicker to cover more pixels.<br>    if enlarge:<br>        rectStructure = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (enlarge, enlarge))<br>        img_combined = cv2.dilate(img_combined, rectStructure)</pre><pre>    # A simple subtraction to remove the lines from the article image.<br>    result = cv2.subtract(img, img_combined)<br>    result = cv2.bitwise_not(result)<br>    return result</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*rV61v9GE1ov55SPb-pXHXA.jpeg" /><figcaption>Figure 6. The detected lines (top). Before (bottom left) and After (bottom right) border removal.</figcaption></figure><p>This is the final step of using traditional image processing. In the later stage, we will use DAE to denoise the images and perform OCR on them.</p><p>ps: You may notice some processed images differ in the figures. It is because we have adjusted the settings in the pipeline during the course of writing this article. The whole workflow is still the same.</p><h3>Task: “ocr”</h3><h3>Use DAE to denoise the article image</h3><p>Once we finish the steps in the “prep” task, we should be able to get a satisfying “pre-cleaned” article image. It is then predicted by the DAE model to produce an image without noise. For more details on the DAE model, please feel free to visit the previous <a href="https://medium.com/scmp-inside-the-wonton/using-ai-to-denoise-scanned-newspaper-88f4e34f59c0">blog post</a>.</p><p>Before Tesseract starts the OCR process, it will use Otsu algorithm to binarize the image. In our case, we found that simple thresholding is good enough to create a clean and clear image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*NuCluDgW97qOYzyrYVpSjA.jpeg" /><figcaption>Figure 7. Before (left) and after (right) noise removal by DAE + simple threshold.</figcaption></figure><h3>Perform OCR by Tesseract</h3><p>At this stage, all the image processing steps are finished. The denoised image will be processed by Tesseract. The OCR outputs are a text file and a “text-only” PDF. The text file will be parsed and stored in API. The transparent “text-only” PDF will be merged with a PDF containing the original article image, to produce a searchable PDF.</p><h3>Google Colab</h3><p>The DAE model was first trained on an “on-demand” compute instance in AliCloud. We used a GPU-type instance and had to manually install graphic card drivers before TensorFlow can utilize the GPU. When new datasets were available, we had to manually copy the files to the instance. From time to time, we had to wait for an available instance to start the machine for training. Because of these, we switched to use Google Colab.</p><p>Google Colab provides a Jupyter like online service that has integration with Google Drive. We can simply mount our datasets from Google Drive onto the Google Colab instance. And it provides free GPU instances (Nvidia K80s, T4s, P4s and P100s) to run the training. That makes a perfect place for us to experiment with different models and datasets efficiently.</p><p>Our first model was trained from datasets prepared manually. Thanks to my colleague who help to remove the noise by hand. The amount of samples is just enough for the PoC: “To proof that DAE is the right approach to help us clean up the images”. But we need a large number of samples to train a model for production usage, in order to handle the noise patterns over the 100 years news archive.</p><p>We decided to programmatically augment the number of datasets. First, we pick article images that are clean enough to produce high OCR accuracy. Then we randomly select some noise samples from the news archive. During the training process, we use ImageDataGenerator and use a custom preprocessing_function to randomly mix these noise samples into the image for training. This way, our model will be general enough to handle different noise types.</p><h3>Orchestration</h3><p>Since all Newsroom related services are hosted on Kubernetes, it becomes a natural choice to put API and pipeline-related services on Kubernetes.</p><p>Once we finished the upload step, we use a simple python script to go through lists of record IDs from the API, and these IDs are then passed to Celery using RabbitMQ as a message broker. The service prep and ocr subscribes to the RabbitMQ channel, pick up the record ID and go through the above mentioned processes.</p><p>Horizontal Pod Autoscaler (HPA) is set on the “prep” and “ocr” services, with a maximum of 200 pods running at the same time. Because we are using <a href="https://partners-intl.aliyun.com/vodafone/products/elastic-container-instance">AliCloud Elastic Container Instance</a> (ECI), we are able to create pods outside our cluster nodes. AliCloud will manage to provision compute instances to run those pods, and the cost is billed per second. That gives us a very cost-efficient way to run a large amount of short-lived jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*SSiiSxZCQCzIlqHy" /><figcaption>Figure 8. A simple diagram shows the interactions between different components in the project.</figcaption></figure><p>This is the current setup of the OCR project, and we look forward to migrating the improved OCR text into Nexus.</p><h3>Special thanks</h3><ul><li>Celery</li><li>FastAPI</li><li>Kubernetes</li><li>OpenAPI Generator</li><li>OpenCV</li><li>Tensorflow</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8712f8743561" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scmp-inside-the-wonton/pipeline-to-process-and-ocr-historical-news-archive-8712f8743561">Pipeline to process and OCR historical news archive</a> was originally published in <a href="https://medium.com/scmp-inside-the-wonton">SCMP — Inside the Wonton</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using AI to denoise scanned newspaper]]></title>
            <link>https://medium.com/scmp-inside-the-wonton/using-ai-to-denoise-scanned-newspaper-88f4e34f59c0?source=rss-acf6fbed038f------2</link>
            <guid isPermaLink="false">https://medium.com/p/88f4e34f59c0</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[newspapers]]></category>
            <category><![CDATA[eda]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Steven Yeung]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 05:11:16 GMT</pubDate>
            <atom:updated>2020-09-25T05:11:16.484Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using AI to denoise scanned newspapers</h3><h3>TL;DR</h3><p>We are in the process of improving OCR text of our historical digital news archive. The archive comprises of PDFs, produced from microfilms and original news prints. The PDF quality varies, resulting in a poor OCR result. Our supposition is that if the image quality can be improved, the OCR accuracy will in turn improve.</p><p>We came across a machine learning technique named Denoising Autoencoder (DAE), it encodes and decodes image by running it through a convolutional neural network (CNN). Since this is a lossy process, the model is trained to ignore unwanted signals: “the noise”. The end result is a clearer PDF image.<br>Although more effort is needed to refine the model, results so far are promising.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l63tgOiD3LPb8NUG6fgf3w.png" /><figcaption><em>News in 1903. Left: Scanned and OCR by vendors; Right: Cleaned by DAE and OCR by Tesseract.</em></figcaption></figure><h3>Background</h3><p>We have over 100 years of news archive in the form of microfilms and news print. They were scanned by a vendor, and converted to PDF and TIFF formats. The files were then passed to another vendor to extract the text (OCR).</p><p>The OCR results were extremely poor, due to wear and tear of the microfilms through usage. Although not visible to human eyes, vertical lines are appeared across the text in the scans. Ink patches and dense background noise due to paper quality and the printing processes, as well as misaligned and skewed text added to the complexity.</p><p>The OCR vendor we engaged made our effort to re-OCR job easier. Articles are clipped into individual PDFs, accompanied by an XML file containing the article title, sub-title, byline and category. The XML file also details the coordinates of the articles in the original paper, in case we have to go back to the original for reference.</p><p>Therefore, all we have to do is to find the best way to denoise the PDF images and OCR again with Tesseract.</p><h3>The traditional approaches</h3><p>At the very beginning, we looked for a simple image processing technique to remove the noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPCd_VsXP3tS2n4VHVuUdg.png" /></figure><p>Although most of the noise was removed from the above experiments, some character details were also eroded.</p><p>Median blurring is very effective against salt-and-pepper noise that we are seeking to remove, but the lines remained. The method dilation and erosion had a better result than median blurring, but traces of noises remain across the whole paragraph, which affected the OCR accuracy. Most of our scanned newspapers are already binarized, so the adaptive threshold can not help in this case. Adaptive threshold works best when there is a considerable variation in the background intensity, where text is usually darker than the background noise.</p><h3>The AI approach</h3><p>After several trials of using the above technique, we started to look for a more “intelligent” approach. We came across the term “autoencoder”.</p><h4>Denoising Autoencoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*wKE69-fX180Q_gkzYzGbwg.png" /><figcaption><em>Image courtesy of </em><a href="https://commons.wikimedia.org/wiki/File:Autoencoder_structure.png"><em>Chervinskii</em></a></figcaption></figure><p>Denoising Autoencoder (DAE) is a type of artificial neural network that composes of an encoder and a decoder. The encoder converts the input into a compressed representation, while the decoder reconstructs the compressed form to as close as possible to its original input. Convolutional Neural Network (CNN) is used for feature engineering, which is to extract and select useful features in the process.</p><p>Our goal is to train a neural model to output a cleaned image from the original noisy one. Under supervised training, we feed the model with the noisy image, encoder learns what features to retain and ignore the “noises”. The decoder learns to generate the output and compare the result with our manually cleaned samples. We repeat the training process until validation accuracy can no longer be improved, and before overfitting happens.</p><p>The encoding process is lossy, and we may use the encoder to compress images. This is similar to how the JPEG works. But in general, the compression works better in JPEG, as the encoder only works best with the type of data it is trained with.</p><h4>DAE example with Keras</h4><pre>input_img = Input(shape=(28, 28, 1))</pre><pre>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(input_img)<br>x = MaxPooling2D((2, 2), padding=&#39;same&#39;)(x)<br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>encoded = MaxPooling2D((2, 2), padding=&#39;same&#39;)(x)</pre><pre>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(encoded)<br>x = UpSampling2D((2, 2))(x)<br>x = Conv2D(32, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>x = UpSampling2D((2, 2))(x)<br>decoded = Conv2D(1, (3, 3), activation=&#39;sigmoid&#39;, padding=&#39;same&#39;)(x)</pre><pre>autoencoder = Model(input_img, decoded)<br>autoencoder.compile(optimizer=&#39;adadelta&#39;, loss=&#39;binary_crossentropy&#39;)</pre><p><em>Code sample courtesy of </em><a href="https://blog.keras.io/building-autoencoders-in-keras.html"><em>Francois Chollet</em></a></p><p>The input image is 28 by 28 pixels with 1 channel (1 color, grayscale) from the example above. The input is being processed with 2 convolutions. Each convolution layer has 32 filters with a 3x3 kernel to produce 32 feature maps. These feature maps are then downsized (subsampling) by a 2x2 kernel, resulting in a smaller feature map.</p><p>Although the information is lost, this helps speed up the training process and reduce system resource usage. After the 2 convolutions, the compressed representation will be reconstructed to produce the output. Another 2 convolutions are used here. This time, Upsampling is used to restore the output size to match the input size. In the last convolution layer, notice the number of filters set to 1 because we need to reduce the channel to 1 to match the input channel number.</p><p>If you run the above python code together with autoencoder.summary(), you will get the following model details. The shape is the same for layer input_1 and conv2d_4.</p><pre>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #<br>=================================================================<br>input_1 (InputLayer)         [(None, 28, 28, 1)]       0<br>_________________________________________________________________<br>conv2d (Conv2D)              (None, 28, 28, 32)        320<br>_________________________________________________________________<br>max_pooling2d (MaxPooling2D) (None, 14, 14, 32)        0<br>_________________________________________________________________<br>conv2d_1 (Conv2D)            (None, 14, 14, 32)        9248<br>_________________________________________________________________<br>max_pooling2d_1 (MaxPooling2 (None, 7, 7, 32)          0<br>_________________________________________________________________<br>conv2d_2 (Conv2D)            (None, 7, 7, 32)          9248<br>_________________________________________________________________<br>up_sampling2d (UpSampling2D) (None, 14, 14, 32)        0<br>_________________________________________________________________<br>conv2d_3 (Conv2D)            (None, 14, 14, 32)        9248<br>_________________________________________________________________<br>up_sampling2d_1 (UpSampling2 (None, 28, 28, 32)        0<br>_________________________________________________________________<br>conv2d_4 (Conv2D)            (None, 28, 28, 1)         289<br>=================================================================<br>Total params: 28,353<br>Trainable params: 28,353<br>Non-trainable params: 0<br>_________________________________________________________________</pre><p>We are still looking for a good model that can handle our use case, but choosing DAE is definitely the right approach to solve our problem “intelligently”.</p><h3>References</h3><ul><li><a href="https://blog.keras.io/building-autoencoders-in-keras.html">https://blog.keras.io/building-autoencoders-in-keras.html</a></li><li><a href="https://en.wikipedia.org/wiki/Autoencoder">https://en.wikipedia.org/wiki/Autoencoder</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88f4e34f59c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scmp-inside-the-wonton/using-ai-to-denoise-scanned-newspaper-88f4e34f59c0">Using AI to denoise scanned newspaper</a> was originally published in <a href="https://medium.com/scmp-inside-the-wonton">SCMP — Inside the Wonton</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>