Skip to main content

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​

DetailValue
Class NameCompareService
Type@Service (Spring Component)
DependenciesQuadTreeService, ContourService, RegionMaskService
Key Functioncompare(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​

  1. Start Timer: Records System.nanoTime() to calculate the total execution duration for performance logging.
  2. Comparison Image Loading:
    • The compareFile (img2) is temporarily saved to the file system using Files.createTempFile().
    • OpenCV reads the file into a Mat object using Imgcodecs.imread().
    • Validation: Checks if img2 is empty (img2.empty()), returning an error if the file is corrupt or not an image.

2.2 Region Mask Application​

  1. The regionJson string (defining select or ignore areas) is passed to the RegionMaskService.apply().
  2. 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.

StepService/Function UsedDescription
1. Load Base ImageImgcodecs.imread()Loads each baseFile (img1) into an OpenCV Mat.
2. Pre-Checkimg1.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 DifferencequadTree.diff(img1, img2)The QuadTreeService runs its recursive algorithm to generate a diffMask (a binary image where white pixels indicate differences).
4. Apply Region FiltercontourService.applyRegionMask(diffMask, regionMask)The initial diffMask is filtered by the regionMask to ignore or select differences based on user configuration.
5. Calculate ScoreCore.countNonZero(masked)Calculates the final diffScore by counting the total number of non-zero pixels (differences) in the filtered mask.
6. Best Match UpdateInternal LogicIf 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​

  1. Contour Detection: The final bestMask is passed to the ContourService.findContours(). This process groups neighboring difference pixels into bounding boxes.
  2. Drawing Boxes: The comparison image (img2.clone()) is passed to ContourService.drawTransparentBoxes(), which draws semi-transparent rectangles over the detected differences (bounding boxes).
  3. Performance: The total execution time is calculated and stored in the timings map.
  4. Response:
    • If bestDiff == 0 (no differences found), ResponseHandler.identical() is called.
    • Otherwise, ResponseHandler.different() is called, using the final output image with the drawn boxes and the list of bounding boxes.

3. Service Dependencies​

DependencyResponsibility
QuadTreeServiceExecutes the pixel-level difference calculation, returning a raw binary mask of differences.
RegionMaskServiceParses user JSON input to create an OpenCV binary mask for selective comparison areas.
ContourServiceConverts scattered difference pixels (diffMask) into grouped, rectangular bounding boxes and draws these boxes onto the final output image.
ResponseHandlerUtility to construct standardized ResponseEntity objects for success, difference, and error conditions.