Automated Pill Counting Using Digital Image Processing in MATLAB

This project presents an automated system for counting the number of white pills present in a digital image using fundamental digital image processing techniques implemented in MATLAB.

In Connect with Author

Domain: Digital Image Processing

Tool Used: MATLAB (Image Processing Toolbox)

Date: August 2026

Abstract

Manual counting of pills in pharmaceutical packaging, quality control, and inventory management is time-consuming, repetitive, and prone to human error, especially when large batches must be verified quickly and accurately. This project presents an automated system for counting the number of white pills present in a digital image using fundamental digital image processing techniques implemented in MATLAB. The system uses grayscale conversion, noise removal through averaging and median filtering, contrast enhancement, Otsu-based automatic thresholding, and morphological operations such as opening, closing, and hole filling to isolate individual pills from the background. Connected component labeling is then applied to identify and count each isolated pill region, and the results are visually verified by overlaying bounding boxes and numeric labels on the original image. The proposed system offers a fast, low-cost, and reasonably accurate alternative to manual counting and can be extended for use in pharmaceutical packaging lines, hospital dispensaries, and automated quality-inspection systems.

Table of Contents

  1. Introduction
  2. Objectives
  3. Literature Background / Theoretical Concepts
  4. System Requirements
  5. Proposed Methodology
  6. Algorithm and Flowchart
  7. MATLAB Implementation (Code)
  8. Detailed Explanation of Code Modules
  9. Results and Discussion
  10. Advantages
  11. Limitations
  12. Applications
  13. Future Scope
  14. Conclusion
  15. References

1. Introduction

Digital Image Processing (DIP) refers to the use of computer algorithms to perform processing operations on digital images. It plays a vital role in numerous real-world applications such as medical diagnosis, industrial automation, quality inspection, remote sensing, and security. One practical application of DIP is object counting — automatically determining the number of distinct objects present in an image.

In the pharmaceutical industry, accurately counting pills, tablets, or capsules is essential during packaging, dispensing, and quality assurance. Manual counting is slow and susceptible to mistakes, particularly when dealing with large volumes. This project automates the process of counting white pills captured in a single image using MATLAB's Image Processing Toolbox, applying a structured pipeline of filtering, noise removal, segmentation, and morphological analysis.

2. Objectives

  • To design an automated image processing pipeline capable of detecting and counting white pills in an image.
  • To apply noise reduction techniques (averaging and median filtering) to improve image quality before segmentation.
  • To implement automatic thresholding (Otsu's method) for separating pills from the background.
  • To apply morphological operations to refine the segmented regions and eliminate noise artifacts.
  • To label and count connected components representing individual pills.
  • To visually validate results by displaying bounding boxes and count labels on the original image.

3. Literature Background / Theoretical Concepts

3.1 Grayscale Conversion

A color image is represented using three channels — Red, Green, and Blue (RGB). For object detection tasks where color information is not essential, converting the image to a single-channel grayscale image reduces computational complexity while preserving the structural and intensity information needed for segmentation.

3.2 Image Noise and Filtering

Digital images often contain noise introduced during acquisition (e.g., camera sensor noise, poor lighting, compression artifacts). Filtering techniques are used to suppress this noise:

  • Averaging (Mean) Filter: Replaces each pixel with the average intensity of its neighborhood. It is simple and effective for general smoothing but tends to blur sharp edges.
  • Median Filter: Replaces each pixel with the median intensity value of its neighborhood. It is highly effective against salt-and-pepper noise and, unlike the mean filter, preserves edges better because it does not average across boundaries.

3.3 Contrast Enhancement

Contrast enhancement redistributes the intensity histogram of an image so that the difference between foreground (pills) and background becomes more distinct, which improves the reliability of the subsequent thresholding step.

3.4 Thresholding and Otsu's Method

Thresholding converts a grayscale image into a binary (black and white) image by classifying each pixel as either foreground or background based on an intensity cutoff. Otsu's method automatically calculates the optimal threshold by minimizing the intra-class variance (or equivalently maximizing the inter-class variance) between the two pixel classes, removing the need for manual threshold selection.

3.5 Morphological Operations

Morphological operations process images based on shape using a structuring element:

  • Erosion: Shrinks white regions, removing small protrusions and thin connections.
  • Dilation: Expands white regions, filling small gaps.
  • Opening (erosion followed by dilation): Removes small noise objects while preserving the shape and size of larger objects.
  • Closing (dilation followed by erosion): Fills small holes and gaps within objects.

3.6 Connected Component Labeling

Connected component labeling scans a binary image and assigns a unique integer label to each group of connected foreground pixels. Each labeled group corresponds to one distinct object — in this case, one pill — allowing the total count to be obtained directly as the number of labels found.

4. System Requirements

4.1 Software

Component Requirement
Platform MATLAB R2018a or later
Toolbox Image Processing Toolbox
Operating System Windows / macOS / Linux

4.2 Hardware

  • A standard PC/laptop capable of running MATLAB (minimum 4 GB RAM recommended).
  • Input image of white pills (JPEG/PNG), ideally photographed against a plain, contrasting background.

5. Proposed Methodology

The system follows a sequential image processing pipeline, where the output of each stage becomes the input to the next. The overall methodology consists of the following stages:

  • Step 1 — Image Acquisition: The input RGB image containing white pills is read into MATLAB using imread().
  • Step 2 — Grayscale Conversion: The RGB image is converted to a single-channel grayscale image using rgb2gray() to simplify further processing.
  • Step 3 — Noise Removal: An averaging filter and a median filter are applied. The median-filtered result is carried forward as it better preserves pill edges while removing noise.
  • Step 4 — Contrast Enhancement: imadjust() stretches the intensity range to increase the visual and numerical separation between pills and background.
  • Step 5 — Thresholding: Otsu's method (graythresh()) automatically computes the optimal threshold, and imbinarize() converts the image into a binary mask.
  • Step 6 — Morphological Refinement: Opening removes small noise specks, closing and hole-filling consolidate each pill into a single solid region, and bwareaopen() removes any remaining small artifacts.
  • Step 7 — Connected Component Labeling: bwlabel() identifies each isolated white region and assigns it a unique label; the number of labels equals the number of detected pills.
  • Step 8 — Feature Extraction & Visualization: regionprops() extracts the centroid, area, and bounding box of each labeled pill, which are drawn back onto the original image for visual verification.
  • Step 9 — Result Reporting: The total pill count and the area of each detected pill are printed to the Command Window, with the count also displayed as the figure title.

6. Algorithm and Flowchart

Stage MATLAB Function(s) Used Purpose
Read Image imread() Load the original RGB image
Grayscale Conversion rgb2gray() Reduce to single intensity channel
Noise Removal fspecial(), imfilter(), medfilt2() Suppress noise while preserving structure
Contrast Enhancement imadjust() Increase foreground-background separation
Thresholding graythresh(), imbinarize() Convert to binary image using Otsu's method
Morphological Cleanup imopen(), imclose(), imfill(), bwareaopen() Remove noise, fill holes, merge fragmented regions
Labeling bwlabel() Assign unique ID to each connected pill region
Feature Extraction regionprops() Get centroid, area, bounding box of each pill
Visualization & Output imshow(), rectangle(), text(), fprintf() Display and report final pill count

Textual Flow: Input Image → Grayscale → Noise Removal (Averaging / Median) → Contrast Enhancement → Otsu Thresholding → Morphological Opening → Closing + Hole Filling → Small Object Removal → Connected Component Labeling → Region Property Extraction → Count Display & Visualization.

7. MATLAB Implementation (Code)

The complete MATLAB implementation used in this project is listed below. The code is modular and organized into clearly commented sections corresponding to each stage of the methodology.

clc; clear; close all; 

%% 1. READ THE IMAGE
originalImage = imread('pills.jpg');
imshow(originalImage); title('Original Image'); 

%% 2. CONVERT TO GRAYSCALE
grayImage = rgb2gray(originalImage); 

%% 3. NOISE REMOVAL
avgFilter    = fspecial('average', [3 3]);
avgFiltered  = imfilter(grayImage, avgFilter);
medianFiltered = medfilt2(grayImage, [3 3]);
filteredImage  = medianFiltered; 

%% 4. CONTRAST ENHANCEMENT
enhancedImage = imadjust(filteredImage); 

%% 5. THRESHOLDING (Otsu's Method)
level = graythresh(enhancedImage);
binaryImage = imbinarize(enhancedImage, level); 

%% 6. MORPHOLOGICAL OPERATIONS
se = strel('disk', 3);
opened  = imopen(binaryImage, se);
closed  = imclose(opened, se);
filledImage  = imfill(closed, 'holes');
cleanedImage = bwareaopen(filledImage, 150); 

%% 7. CONNECTED COMPONENT LABELING & COUNTING
[labeledImage, numPills] = bwlabel(cleanedImage);
stats = regionprops(labeledImage, 'Centroid','Area','BoundingBox'); 

%% 8. DISPLAY RESULT
imshow(originalImage); hold on;
title(['Total White Pills Detected: ', num2str(numPills)]);
for k = 1:numPills
    rectangle('Position', stats(k).BoundingBox, 'EdgeColor','r','LineWidth',2);
    text(stats(k).Centroid(1), stats(k).Centroid(2), num2str(k), ...
        'Color','yellow','FontWeight','bold','HorizontalAlignment','center');
end
hold off; 

%% 9. PRINT RESULT
fprintf('Total number of white pills detected: %d\n', numPills);

(Note: The full commented version with figure titles for every intermediate stage is provided in My GitHub Repository .)

VISIT THE GITHUB TO GET THE CODE FILE  

 View on GitHub

8. Detailed Explanation of Code Modules

8.1 Image Acquisition

imread('pills.jpg') loads the image file into MATLAB as a 3-D numeric matrix (height × width × 3 for RGB). This raw image serves as the reference for the final visualization step, where results are overlaid on the unmodified original.

8.2 Grayscale Conversion

rgb2gray() converts the 3-channel RGB matrix into a single 2-D intensity matrix using a weighted sum of the R, G, and B channels (approximately 0.30R + 0.59G + 0.11B), reflecting human perceptual sensitivity to each color. This step reduces the data to one-third its original channel depth and is necessary because subsequent operations (filtering, thresholding) are designed for single-channel intensity data.

8.3 Noise Removal — Averaging and Median Filters

fspecial('average',[3 3]) creates a 3×3 convolution kernel where every element equals 1/9. imfilter() convolves this kernel with the grayscale image, replacing each pixel with the mean of its 3×3 neighborhood — this smooths random intensity fluctuations but slightly blurs edges.

medfilt2(grayImage,[3 3]) applies nonlinear median filtering: for every 3×3 neighborhood, the nine pixel values are sorted and the middle (median) value replaces the center pixel. Because it does not average, it removes isolated noise pixels (salt-and-pepper noise) very effectively while keeping pill boundaries sharp — this is why the median-filtered image is chosen as the input to the next stage.

8.4 Contrast Enhancement

imadjust() maps the input intensity range to the full available range (0 to 255 for 8-bit images) using a linear transformation, saturating the bottom 1% and top 1% of pixel values by default. This increases the visual and numerical gap between the bright pills and the darker background, making the automatic threshold in the next step more reliable.

8.5 Thresholding — Otsu's Method

graythresh() implements Otsu's algorithm, which treats the image histogram as two classes (foreground and background) and searches for the threshold level that minimizes the weighted within-class variance of pixel intensities. The returned value (normalized between 0 and 1) is passed to imbinarize(), which sets every pixel above the threshold to 1 (white/foreground) and every pixel below it to 0 (black/background), producing a binary mask of candidate pill regions.

8.6 Morphological Operations

strel('disk',3) defines a disk-shaped structuring element of radius 3 pixels, chosen because pills are roughly circular/oval and a disk-shaped element preserves their natural shape better than a square one.

imopen() performs erosion followed by dilation, which eliminates small, isolated white noise blobs that survived thresholding without significantly shrinking the actual pills.

imclose() performs dilation followed by erosion, sealing small black gaps or notches on the pill boundary caused by uneven lighting or reflections.

imfill(closed,'holes') fills any fully enclosed dark regions inside a pill (for example, a glare spot in the middle of a pill that was misclassified as background), ensuring each pill becomes one solid, uniform blob.

bwareaopen(filledImage,150) removes any remaining connected components smaller than 150 pixels in area, eliminating leftover noise that is too small to be a real pill.

8.7 Connected Component Labeling and Counting

bwlabel() scans the cleaned binary image and assigns a unique integer label (1, 2, 3, …) to every group of 8-connected (or 4-connected) foreground pixels. Its second output, numPills, directly returns the count of distinct labeled regions — this single value is the final answer to "how many pills are in the image."

8.8 Feature Extraction and Visualization

regionprops() computes descriptive properties for every labeled region, including Centroid (geometric center, used to place the pill number), Area (pixel count, used to flag abnormally large or small blobs such as overlapping or broken pills), and BoundingBox (used to draw a rectangle around each detected pill). These are overlaid on the original color image using rectangle() and text(), producing a clearly annotated result for visual confirmation.

8.9 Result Reporting

Finally, fprintf() prints the total pill count and the individual area of each detected pill to the Command Window, giving the user both a quick summary and enough detail to manually verify or investigate any suspicious detections (e.g., a pill with double the average area likely indicates two touching pills merged into one blob).

9. Results and Discussion

When executed on a sample image of white pills scattered on a plain, contrasting background, the system successfully isolates each pill as a separate connected region and reports an accurate total count, provided the pills are non-overlapping. The intermediate figures generated by the code (grayscale image, filtered images, binary mask, and morphologically cleaned mask) allow each stage of the pipeline to be visually inspected and validated. The final annotated image, showing bounding boxes and sequential numbers over each detected pill, provides an intuitive way to visually cross-check the automated count against the original image.

Accuracy is highest when the following conditions are met: uniform lighting across the image, a background color that strongly contrasts with the white pills, and pills that do not touch or overlap one another. Deviations from these conditions — such as touching pills, shadows, or uneven illumination — can cause under-counting (two touching pills labeled as one) or over-counting (a single pill split into two labels due to a shadow or reflection).

 




 

10. Advantages

  • Fully automated — removes the need for manual, error-prone counting.
  • Fast execution — processes an image and returns a count within seconds.
  • Uses adaptive thresholding (Otsu's method), so it does not require manual tuning of a brightness cutoff for every new image.
  • Modular pipeline — each stage can be independently improved or replaced without redesigning the whole system.
  • Provides visual proof of the count (bounding boxes and labels), which builds user trust in the result.

11. Limitations

  • Overlapping or touching pills may be merged into a single connected region, leading to under-counting.
  • Performance is sensitive to background contrast and lighting uniformity; a cluttered or similarly colored background reduces accuracy.
  • The system is designed for white/light-colored pills; colored pills or transparent capsules would require adapted color-based segmentation.
  • Reflective or glossy pill coatings can cause bright glare spots that occasionally interfere with segmentation.

12. Applications

  • Pharmaceutical packaging lines for automated tablet/capsule counting before bottling.
  • Hospital and pharmacy dispensaries for verifying prescription quantities.
  • Quality control and inspection systems to detect broken, missing, or extra pills in a blister pack.
  • Inventory and stock verification in warehouses and drug manufacturing units.
  • Educational demonstration of core digital image processing concepts (filtering, segmentation, morphology, object counting).

13. Future Scope

  • Implement watershed segmentation or distance-transform-based splitting to correctly separate touching/overlapping pills.
  • Extend the system to classify pills by color, shape, or size using machine learning, in addition to counting them.
  • Integrate the system with a live camera feed for real-time counting on a packaging conveyor belt.
  • Deploy the algorithm on embedded hardware (e.g., Raspberry Pi with a camera module) for a low-cost, standalone counting device.
  • Add automatic defect detection (cracked, discolored, or malformed pills) alongside counting.

14. Conclusion

This project successfully demonstrates an automated white pill counting system built entirely using fundamental digital image processing techniques in MATLAB. By combining grayscale conversion, noise-reduction filtering, Otsu-based thresholding, and morphological refinement with connected component labeling, the system reliably converts a raw photograph of scattered pills into an accurate, visually verifiable count. The approach requires no manual parameter tuning for the threshold and generalizes well across images with a consistent background and lighting setup. While overlapping pills remain a challenge, the modular design of the pipeline makes it straightforward to extend with more advanced segmentation techniques such as watershed transformation. Overall, the project illustrates how classical image processing methods, when combined thoughtfully, can solve a genuinely useful real-world counting problem with minimal computational cost.

15. References

  1. Gonzalez, R. C., & Woods, R. E., Digital Image Processing, 4th Edition, Pearson.
  2. MathWorks Documentation — Image Processing Toolbox: https://www.mathworks.com/help/images/
  3. MathWorks Documentation — graythresh, imbinarize, regionprops, bwlabel functions.
  4. Otsu, N. (1979). "A Threshold Selection Method from Gray-Level Histograms." IEEE Transactions on Systems, Man, and Cybernetics.
  5. Gonzalez, R. C., Woods, R. E., & Eddins, S. L., Digital Image Processing Using MATLAB, 2nd Edition.

 

 

Support My Work with a Cup of Chai!


If you are located in India, I kindly request your support through a small contribution.

Please note that the UPI payment method is only available within India.

Chai

Accepted Payment Methods: Google Pay, PhonePe, PayTM, Amazonpay  UPI 

UPI ID

haneenthecreate@postbank

 

If you are not located in India , Do the Payments via BUY ME A COFEE

                                                 

 

Wishing you a wonderful day!


*

Post a Comment (0)
Previous Post Next Post