1 Introduction
Food allergy is a major public health issue, defined by the World Health Organization (WHO) as a hypersensitivity reaction involving the immune system [1]. These reactions, often IgE-mediated, can trigger severe symptoms like hives and vomiting, and can even lead to death [2]. In Brazil, an estimated 6-8% of children and around 3% of adults have some form of food hypersensitivity, with common allergens including milk, eggs, and wheat [3,4].
Preventing allergic reactions primarily involves avoiding trigger foods, making accurate food labels essential [4]. Global efforts, such as the WHO's 1992 Codex Alimentarius, established labeling recommendations [5]. In Brazil, the “Põe no Rótulo” campaign, in 2014, championed clear labeling [6], leading to the Brazilian Health Regulatory Agency's (ANVISA) Collegiate Board Resolution (RDC) No. 26/2015 (later RDC No. 727/2022), which mandated readable allergen warnings on processed foods [7,8]. Additionally, RDC No. 727/2022 lists the 18 main allergen-causing foods, including milk, eggs, soy, and wheat, among others. However, for a single food item, a variety of terms may appear on the label. For instance, there are 43 distinct terms or ingredients representing the presence of milk, 40 for wheat, 35 for soy, and 23 for eggs [9]. It is also worth noting that among these identified variations, spelling differences may also occur, further expanding the variability of terms and, consequently, the difficulty in interpreting them. Furthermore, factors like variations in packaging materials (e.g., polypropylene, polyethylene, biaxially oriented polypropylene film) and colors can impede label readability. These material differences, alongside texture and color variations, pose a challenge for consumers.
Individual challenges, such as difficulties in reading or interpreting, further complicate label comprehension. Data from the 2022 Continuous National Household Sample Survey (PNAD Contínua) indicates that 8.9% of the Brazilian population has some form of disability, including visual impairments (3.1%) and learning disabilities (2.6%). Packaging size, information distribution, or font contrast can exacerbate these difficulties [10].
Given these complexities, ensuring allergic consumers correctly read ingredient lists remains challenging. Mobile applications, such as “Desrotulando” and “Loomos,” offer assistance. This work utilizes “Aillergic” [11], an application designed to identify allergens from food label images. “Aillergic” integrates natural language processing (NLP) [12] and optical character recognition (OCR) [13] application programming interfaces (APIs): the OCR extracts text from images, connecting the captured images to the NLP algorithm. Although the OCR API [13] is functional, refining image preprocessing is needed to improve results across diverse labels and packaging.
This study is part of a broader project validating a mobile application for allergen identification on food labels. Specifically, this work comparatively analyzes OCR tools and digital image preprocessing techniques to enhance image quality, thereby optimizing Aillergic’s OCR API results and improving the accuracy of allergen identification.
2 Methods
The methodology adopted for the development of the study consists of five stages: i) definition of possible digital image preprocessing techniques based on the issues identified in the first version of the application; ii) small-scale testing to narrow down the tools to be used; iii) creation of an image database for testing; iv) development of a representational state transfer (REST) API; and v) testing.
2.1 Definition Of Pre-processing Techniques
Image preprocessing consists of applying techniques intended to improve the quality and interpretability of input images, including distortion correction, enhancement of relevant features, and noise reduction through filtering methods [14]. Preprocessing strategies vary according to the characteristics of the image and the objectives of subsequent processing stages. In the present study, the selected techniques were based on literature focused on OCR optimization, particularly for the TesseractOCR engine.
A color model defines a three-dimensional coordinate system in which each color is represented by a single point, with RGB (red, green, blue) being the most common hardware-oriented model [15]. Grayscale conversion reduces this three-channel representation to a single intensity channel; the luminosity method was adopted, which applies a weighted average prioritizing green tones in accordance with human visual perception [16].
Contrast refers to the difference in gray levels across an image and can directly affect OCR interpretation [17]. Contrast-limited adaptive histogram equalization (CLAHE) applies localized histogram equalization with contrast limiting, reducing the risk of noise amplification compared to global equalization [18].
Binarization converts an image into a binary black-and-white representation by classifying each pixel as foreground or background according to a threshold value [19]. TesseractOCR uses Otsu's global thresholding by default, which may underperform on images with uneven illumination or colored backgrounds [20]; adaptive thresholding, which dynamically adjusts the threshold according to local image characteristics, was adopted after yielding superior results.
Noise refers to unwanted variations in pixel values arising from image capture conditions or compression artifacts, corrected through spatial filters, which are matrix-based operations applied via convolution across image pixels [15]. Two filters were evaluated: the Gaussian filter, a linear low-pass filter effective against additive random noise, and the median filter, a nonlinear edge-preserving filter for salt-and-pepper noise [21]. The Gaussian filter was retained in the final pipeline, applied prior to binarization.
Mathematical morphology provides set-theory-based operations for shape analysis, whose fundamental operations, erosion and dilation, are combined into opening (erosion followed by dilation) and closing (dilation followed by erosion) to remove noise and fill gaps in binary images [15]. In this study, opening followed by closing was applied after binarization to reduce impulse noise caused by label textures, which could otherwise be misinterpreted by the OCR engine as punctuation or accent marks.
During the validation tests of the first version of the Aillergic OCR API [13], labels on cylindrical packaging, colored backgrounds, and low-contrast images yielded results below expectations. Based on these findings, we adopted CLAHE, adaptive binarization, Gaussian filtering prior to binarization, and morphological filtering after binarization. Additionally, EasyOCR, a Python library applying deep learning for text recognition in natural scenes [22], was introduced for comparative evaluation against TesseractOCR [23].
2.2 Definition Of The Image Database
Currently, no publicly available datasets or image repositories specifically focused on ingredient lists in Portuguese were identified, and access to the 72 images used in the validation of the first version of the application could not be obtained. Therefore, a new dataset of 87 images was created, with a greater focus on labels from packaging types that present challenges for OCR extraction, such as aluminum cans, chocolates in blister packs, and cylindrical containers. The dataset is publicly available on Kaggle, along with the official transcription of each label.
2.3 Development Of The Rest Api
The first version of the Aillergic OCR API was developed in Java using Spring Boot [13]. However, one of the issues encountered was the limitation of libraries such as OpenCV in Java, as the most recent updates to image processing tools are primarily focused on Python. To facilitate the execution of pre-OCR pipelines and improve integration with the OCR engine itself, the current version of the API was developed in Python 3 using the Django framework. The API includes two endpoints: a POST endpoint for submitting an image for OCR processing, and a GET endpoint for retrieving information stored in the database.
The database used is a non-relational MongoDB database [24], designed to store the original product description and the transcription generated by the OCR (for better visualization, the transcripts were also included in the Kaggle dataset).
2.4 Testing And Evaluation
OCR performance was evaluated using Levenshtein distance similarity, which quantifies the proportion of character-level edits required to transform the OCR output into the official transcription. Each of the 87 images was submitted to the API under different preprocessing configurations, and the resulting transcriptions were compared against the manually validated ground-truth labels available in the dataset. Similarity scores were computed per image and averaged across the dataset for each preprocessing combination. EasyOCR was evaluated under the same metric for selected pipeline configurations, enabling direct comparison with TesseractOCR results.
2.5 Ethical Aspects
All stages of the project were conducted using texts available on labels of industrialized food products, without the application, testing, or validation involving human participants. Therefore, as this is a technological study that does not involve research with human subjects, it is in accordance with Resolution No. 510, of April 7, 2016, of the Brazilian National Health Council, and does not require submission to a Research Ethics Committee.
3 Results
Considering that the main focus for improving the first version of the API was to enhance results for low-quality images, colored labels, packaging with high reflectivity, and difficult-to-read labels, the primary emphasis of the tests was on reducing image noise and standardizing color scales to optimize OCR performance.
The initial proposed pipeline consisted of converting the image to grayscale, performing histogram equalization, followed by binarization. However, the issue with this flow was that different types of packaging require different adjustments, and applying these processes indiscriminately to all input images substantially worsened the results.
To address this, the first preprocessing algorithm tested on all 87 images conditioned the modifications as follows: all images are initially converted to grayscale, and then the predominant background color is analyzed to determine an average contrast level for the label: if the contrast is adequate for OCR, which typically occurs when the packaging has a gray or black background, the algorithm proceeds; if not, histogram equalization is applied. Figure 1 illustrates an example of a package in which grayscale conversion alone was sufficient to preserve readability, without the need for histogram equalization.
During initial tests, both global and adaptive histogram equalization techniques were evaluated on a smaller image set, with adaptive equalization producing better results in the current context. Thus, CLAHE equalization is applied to images with colored backgrounds, and from the equalized image, inversion and binarization are performed so that the resulting image has a white background with black text, which is ideal for OCR tools. Adaptive thresholding yielded better binarization results compared to Otsu’s method.
One issue encountered was noise caused by image capture and binarization. Tests with median and Gaussian filters before binarization resulted in a Levenshtein distance similarity of around 44% in both cases. Applying only morphological filters raised this value from 44% to 46%, while combining both, with a filter before binarization (in this case, Gaussian) and morphological filtering after, increased the Levenshtein distance similarity to 48%. As both noise reduction approaches yielded improvements, they were included in the final comparative analysis. Figure 2 demonstrates the effect of morphological filtering on a colorful reflective label after adaptive binarization.
The worst Levenshtein distance similarity results were observed in thin cylindrical packaging (first row of Figure 3), metallic low-contrast packaging (second row of Figure 3), and labels containing small or bordered fonts (third row of Figure 3). In contrast, packages with good contrast between text and background, low glare, and adequate character spacing achieved better OCR performance (fourth row of Figure 3).
4 Discussion
Although there are legally established standards for information related to ingredients, there is no standardization in how such information is presented: variations in colors, fonts, font sizes, order of alerts, and even the arrangement of the ingredient list on the packaging can affect the interpretation of the information. Furthermore, there is a wide variety of packaging materials and shapes. Combined, these factors make it difficult to establish a standardized approach for recognizing ingredient lists, making each image uploaded by the user nearly unique. This variability complicates the creation of a unified OCR preprocessing workflow, since correcting an issue encountered in the transcription of one text may introduce failures in another image that initially presented a good Levenshtein distance similarity percentage.
Another challenge in optimizing OCR is parameter tuning. Although the conditional preprocessing workflow illustrated in Figure 4 applies enhancement steps only when necessary, it is not possible to achieve ideal results for all inputs because each image presents specific, and sometimes no, preprocessing requirements that cannot be addressed by universal parameters. One example encountered during the project development involved kernel sizes for sharpening blurred images. The initial sharpening filter was ultimately removed from the final workflow because it substantially worsened the results for many images. Similarly, thresholding and binarization parameters were adjusted to intermediate values in order to minimize negative impacts across different image categories, several of which are illustrated in Figure 3.
Finally, the lack of contextual focus for OCR is also a hindrance, as the tool cannot define the execution focus in images containing a lot of information (such as a full package).
One possible way to address this limitation is the use of generative artificial intelligence (AI) models for text extraction, since each prompt execution can adapt dynamically to the characteristics of the input image. To explore this possibility, preliminary tests were conducted using the Gemini 2.5 Pro model and ChatGPT with images that had previously shown low similarity scores in the proposed preprocessing workflows, including energy drink cans, sardine cans, a colorful metallic can, and a soft drink bottle.
Although the free version of ChatGPT was unable to process the images adequately, Gemini 2.5 Pro successfully extracted the complete text from all tested images, achieving Levenshtein similarity scores between 82% and 100%. For comparison, the same images achieved 0% similarity using the preprocessing workflows developed in this study, and less than 70% similarity even when the images were manually cropped to focus exclusively on the ingredient list (Table 2).
When asked about the sources used to identify the “ingredient list” block, Gemini states that its training base is extensive and cites sources such as product databases, e-commerce data, technical and regulatory documents, web scraping from sites displaying packaging and labels in some form, and digitized tags. Considering the image database and information used for model training, even if a pre-trained model for identifying the “ingredient list” block on packaging is developed in the future, it is unlikely that results will be as good as those of a generative AI in the near future.
However, it is worth noting that implementing a generative model in the project would require paying per-token usage, which would generate high costs for Aillergic, making it unfeasible at this time.
5 Conclusion
Image processing techniques proved useful for improving OCR performance, but the lack of standardization in layouts, especially with complex designs, different packaging types, color variations, and fonts, limits optimization. As in the first version of the service, flat packages made of low-reflective materials such as cardboard, with simple layouts, yielded better results and did not require preprocessing. In contrast, packages made of materials that reflect more light, such as aluminum and regenerated cellulose (cellophane), labels with elaborate layouts (such as some soft drinks and sardine cans), and cylindrical and/or small packages that complicate image capture, showed varied results even with preprocessing.
Overall, there was an improvement in text extraction; however, in some cases, such as long aluminum cans with colored backgrounds or small candies wrapped in cellophane with extremely small text fonts, substantial improvements were not achieved. Regarding the optical character recognition tool, TesseractOCR remains the best option in terms of computational performance. Although EasyOCR yielded better results on some images with low similarity scores in TesseractOCR, it is a tool that requires high memory consumption, increasing the application’s execution time. It is also undeniable that labels on flat packages perform better.
Regarding the API, the shift from Java to Python facilitated integration with image processing libraries and tools.
For future work, it is suggested to find alternatives to overcome the lack of layout standardization, such as training a pre-trained model for text extraction and region of interest detection; however, this also requires expanding the training image database.