CompareService
CompareService.java
The CompareService is the core engine of the Image Comparison API, orchestrating the entire workflow from file handling to difference calculation and result preparation using OpenCV.
1. Overview and Initialization
| Detail | Value |
| Class Name | CompareService |
| Type | @Service (Spring Component) |
| Dependencies | QuadTreeService, ContourService, RegionMaskService |
| Key Function | compare(MultipartFile[] baseFiles, MultipartFile compareFile, String regionJson) |
Export to Sheets
OpenCV Native Library: The static block ensures the native OpenCV library is loaded exactly once when the class is initialized, which is mandatory for all org.opencv.* functions to work.
Java
static { System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME); }
2. The compare Method Workflow
The compare method executes a linear flow, primarily managing file I/O, delegation to specialized services, and tracking the best match.
2.1 File Preparation and Validation
- Start Timer: Records
System.nanoTime()to calculate the total execution duration for performance logging. - Comparison Image Loading:
- The
compareFile(img2) is temporarily saved to the file system usingFiles.createTempFile(). - OpenCV reads the file into a
Matobject usingImgcodecs.imread(). - Validation: Checks if
img2is empty (img2.empty()), returning an error if the file is corrupt or not an image.
- The
2.2 Region Mask Application
- The
regionJsonstring (definingselectorignoreareas) is passed to theRegionMaskService.apply(). - The service returns a binary
regionMask** Mat**, which will be used later to filter the detected differences.
2.3 Base Image Iteration and Best Match Logic
The service iterates through all baseFiles to find the one that is the closest match to the compareFile.
| Step | Service/Function Used | Description |
| 1. Load Base Image | Imgcodecs.imread() | Loads each baseFile (img1) into an OpenCV Mat. |
| 2. Pre-Check | img1.size().equals(img2.size()) | Skips comparison if the base image is empty or has a different resolution than the comparison image (size mismatch). |
| 3. Compute Difference | quadTree.diff(img1, img2) | The QuadTreeService runs its recursive algorithm to generate a diffMask (a binary image where white pixels indicate differences). |
| 4. Apply Region Filter | contourService.applyRegionMask(diffMask, regionMask) | The initial diffMask is filtered by the regionMask to ignore or select differences based on user configuration. |
| 5. Calculate Score | Core.countNonZero(masked) | Calculates the final diffScore by counting the total number of non-zero pixels (differences) in the filtered mask. |
| 6. Best Match Update | Internal Logic | If the current diffScore is lower than bestDiff, the current base image (img1), its mask, and its name are stored as the new best match. |
2.4 Final Output Generation
- Contour Detection: The final
bestMaskis passed to theContourService.findContours(). This process groups neighboring difference pixels into bounding boxes. - Drawing Boxes: The comparison image (
img2.clone()) is passed toContourService.drawTransparentBoxes(), which draws semi-transparent rectangles over the detected differences (bounding boxes). - Performance: The total execution time is calculated and stored in the
timingsmap. - Response:
- If
bestDiff == 0(no differences found),ResponseHandler.identical()is called. - Otherwise,
ResponseHandler.different()is called, using the finaloutputimage with the drawn boxes and the list of bounding boxes.
- If
3. Service Dependencies
| Dependency | Responsibility |
QuadTreeService | Executes the pixel-level difference calculation, returning a raw binary mask of differences. |
RegionMaskService | Parses user JSON input to create an OpenCV binary mask for selective comparison areas. |
ContourService | Converts scattered difference pixels (diffMask) into grouped, rectangular bounding boxes and draws these boxes onto the final output image. |
ResponseHandler | Utility to construct standardized ResponseEntity objects for success, difference, and error conditions. |