# Bulk Image Comparison API: Visual Diff & Similarity Score (`bite-sized-insights/visual-diff-api`) Actor

Compare baseline and candidate images in bulk. Get SSIM, perceptual hash distances, pixel diff percentage, changed-region boxes, a diff overlay PNG and a pass/fail verdict per pair. Set thresholds, ignore regions and handle size differences.

- **URL**: https://apify.com/bite-sized-insights/visual-diff-api.md
- **Developed by:** [bite-sized-insights](https://apify.com/bite-sized-insights) (community)
- **Categories:** Developer tools, Automation, AI
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.39 / 1,000 image pair compareds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

**Compare images in bulk** with a **visual diff** and **similarity score**. Give it baseline/candidate pairs (URLs or base64) and get back an **SSIM score**, perceptual hash distances, the share of changed pixels, bounding boxes of the changed regions, a diff overlay image and a pass/fail verdict, from **$0.60 per 1,000 pairs** (failed pairs are free).

Typical uses:

- **Visual regression testing**: compare screenshots before and after a deploy and fail the build on unwanted changes.
- **Design review**: catch unintended layout, colour or text changes between two versions of a page or asset.
- **Near-duplicate detection**: find images that look the same despite resizing or re-compression.
- **Re-encode checks**: verify that a converted or compressed image still looks the same as the original.

### How to compare images

1. Click **Try for free** and add your pairs. Each pair has a `baseline` and a `candidate`, as a URL, a data URI or raw base64.
2. Set `similarityThreshold` (default 0.98). Optionally add `maxDiffPercent` and `ignoreRegions` for areas such as ads or timestamps.
3. Run the Actor. It returns one dataset item per pair, in input order.
4. Read `passed` for the verdict, `ssim` and `pixel_diff_percent` for the numbers, and open `diff_image_url` to see exactly what changed.

### Input

```json
{
  "pairs": [
    {
      "baseline": "https://example.com/before.png",
      "candidate": "https://example.com/after.png",
      "label": "Home page",
      "ignoreRegions": [{ "x": 0, "y": 0, "width": 300, "height": 90 }]
    }
  ],
  "similarityThreshold": 0.98
}
```

| Field | Description |
|---|---|
| `pairs` | Up to 500 pairs: `baseline` and `candidate` (URL or base64), optional `label` and `ignoreRegions` |
| `similarityThreshold` | Minimum SSIM score to pass (default 0.98) |
| `maxDiffPercent` | Optional: also fail when more than this percentage of pixels changed |
| `pixelTolerance` | Per-channel colour difference (0 to 255) still treated as unchanged (default 10) |
| `resizeMode` | Resize the candidate to the baseline size (default), or report an error when the sizes differ |
| `maxDimension` | Larger images are scaled down for the comparison (default 1600, up to 4000) |
| `normalize` | Optionally stretch contrast or convert to grayscale before comparing |
| `ignoreRegions` | Areas to skip (ads, timestamps, carousels) in baseline pixels, applied to every pair |
| `createDiffImage` | Store the diff overlay and return its link (default true) |

Ignored areas are excluded from the score, the changed-pixel percentage and the regions.

#### Images as URL or base64

Each image can be an http(s) URL, a base64 data URI or a raw base64 string, and the two images of a pair can use different forms:

```json
{
  "pairs": [
    { "baseline": "https://example.com/before.png", "candidate": "data:image/png;base64,iVBORw0KGgo..." },
    { "baseline": "iVBORw0KGgoAAAANSUhEUg...", "candidate": "https://example.com/after.png" }
  ]
}
```

- **Detection:** `http://` or `https://` is a URL, `data:` is a data URI, anything else is raw base64. Other schemes (`ftp://`, `file://`) are rejected.
- **Data URIs** must look like `data:image/<format>;base64,<data>`. The media type is not trusted: the image is always decoded and checked, so a `data:image/png` URI holding a JPEG still works.
- **Encoding:** standard or URL-safe alphabet (not mixed). Spaces and line breaks are ignored and missing `=` padding is added. Wrong padding and any other character are rejected.
- **Prefer URLs for large images.** Base64 travels inside the run input, and the Apify platform limits the size of the input (a few MB in total), so a handful of screenshots fits but large files or many pairs do not. Upload files to a key-value store and pass their URLs instead.
- Base64 inputs are never fetched, and the data is never copied into the results or logs.

### Output

One dataset item per pair, in input order.

```json
{
  "index": 1,
  "label": "Home page",
  "baseline_url": "https://example.com/before.png",
  "baseline_input": "https://example.com/before.png",
  "candidate_url": null,
  "candidate_input": "base64 image (48213 bytes)",
  "passed": false,
  "ssim": 0.9412,
  "phash_distance": 4,
  "pixel_diff_percent": 2.31,
  "region_count": 1,
  "regions": [{ "x": 120, "y": 340, "width": 420, "height": 96, "changed_pixels": 8120 }],
  "diff_image_url": "https://api.apify.com/v2/key-value-stores/.../records/diff-00001.png"
}
```

A pair that matches looks like this (shortened):

```json
{ "index": 2, "label": "Pricing page", "passed": true, "ssim": 0.9996, "phash_distance": 0,
  "pixel_diff_percent": 0.0, "region_count": 0, "regions": [], "error": null }
```

| Field | Description |
|---|---|
| `index`, `label` | 1-based position of the pair and the label you gave it |
| `passed` | `true` when `ssim` reaches `similarityThreshold` and any `maxDiffPercent` is respected; `null` on error |
| `ssim` | Structural similarity, 0 to 1 (1 is identical) |
| `phash_distance`, `ahash_distance`, `dhash_distance` | Perceptual hash Hamming distances, 0 to 64 (0 is identical) |
| `pixel_diff_percent`, `changed_pixels` | Share and number of pixels that differ beyond `pixelTolerance` |
| `region_count`, `regions` | Changed areas (`x`, `y`, `width`, `height`, `changed_pixels`) in baseline pixels |
| `baseline_size`, `candidate_size`, `compared_size` | Original sizes and the size used for the comparison |
| `diff_image_url`, `diff_image_key` | Diff overlay PNG (changes in red, regions outlined) and its store key |
| `baseline_url`, `candidate_url` | URL as given, `null` for base64 images |
| `baseline_input`, `candidate_input` | URL as given, or a label like `base64 image (48213 bytes)`; no data echoed |
| `error` | Why the pair could not be compared, otherwise `null` |

Pairs that cannot be compared (unreachable URL, download timed out, invalid base64, not an image, file too large) are returned with an `error` message and no scores, and are not charged.

### Pricing

Pay per event, with no subscription:

- **$0.00005** per run start.
- **$0.60 per 1,000 compared pairs** ($0.0006 each). Failed pairs are free.

Price per compared pair by Apify subscription plan (applied automatically; Gold, Platinum and Diamond share one price):

| Event | Free | Bronze | Silver | Gold+ |
|---|---|---|---|---|
| Compared pair | $0.0006 ($0.60 per 1,000) | $0.00057 ($0.57 per 1,000) | $0.00051 ($0.51 per 1,000) | $0.00039 ($0.39 per 1,000) |

The price depends on your Apify subscription plan and applies automatically, with no setting needed.

Example: 500 pairs that all compare successfully cost 500 x $0.0006 + $0.00005 = $0.30005. If 20 of them fail to download, you pay for 480 pairs. Runs on the free plan and test runs compare the first 10 pairs, so you can try the Actor before paying.

### Limits

| Limit | Value |
|---|---|
| Pairs per run | 500 (10 on the free plan and in test runs) |
| Image size | 25 MB per image, also for decoded base64 |
| Download time | 90 seconds per image URL in total, including redirects; slower downloads are reported as an error |
| Image dimensions | 36 million pixels per image |
| Formats | PNG, JPEG, WebP, GIF (first frame), BMP, TIFF; transparency is flattened onto white |
| URLs | Public http(s) only; private and local addresses are refused |
| Base64 | Counts toward the Apify run input size limit, so prefer URLs for large images |

Oversized files are rejected before they are decoded. Pairs beyond the free-plan cap, and pairs not started once your spending limit is reached, produce no dataset item, and neither do pairs not started because the run was stopped or migrated; compare `index` with your input to spot them. A pair that cannot finish before the run's time limit is not started and gets an item with the error `time_limit: not started, not enough time left in this run`; it is free, so run it again in a new run. Run-level and pair-level `ignoreRegions` together may not exceed 100 per pair.

### Use from the API

Start a run with the [Apify API](https://docs.apify.com/api/v2) or a client library. Python:

```python
from apify_client import ApifyClient

client = ApifyClient("<APIFY_TOKEN>")
run = client.actor("wdm83jKxrIp1ndxgi").call(run_input={
    "pairs": [{"baseline": "https://example.com/before.png", "candidate": "https://example.com/after.png"}],
    "similarityThreshold": 0.98,
})
items = client.dataset(run["defaultDatasetId"]).list_items().items
if not all(item["passed"] for item in items):
    raise SystemExit("Visual regression detected")
```

JavaScript:

```javascript
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: '<APIFY_TOKEN>' });
const run = await client.actor('wdm83jKxrIp1ndxgi').call({
    pairs: [{ baseline: 'https://example.com/before.png', candidate: 'https://example.com/after.png' }],
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
if (items.some((item) => !item.passed)) process.exit(1);
```

The non-zero exit makes the script usable as a step in a CI pipeline.

### FAQ

**Which score should I use?** SSIM is the best single measure of how different two images look. Use the hash distances to find near-duplicates regardless of size or compression, and the pixel diff and regions to see exactly what changed.

**What threshold should I choose?** The default 0.98 flags small but visible changes. Lower it (for example to 0.95) if anti-aliasing or font rendering differences cause false alarms, or raise it for pixel-exact checks. Adding `maxDiffPercent` gives a second, independent limit.

**Why does a one-pixel shift fail?** SSIM compares local structure, so a shifted edge or text line changes the score even though the images look alike. Perceptual hashes tolerate small shifts, so check `phash_distance` as well.

**My screenshots differ in height.** With the default resize mode the candidate is scaled to the baseline size before comparing. Choose the error mode if a size change should count as a failure.

**How do I ignore ads, timestamps or carousels?** Set `ignoreRegions` on the pair or at the top level, in baseline pixels. Those areas are excluded from the score, the changed-pixel percentage and the regions.

**What happens with animated GIFs?** Only the first frame is compared.

**Do images have to be public?** The Actor downloads URLs without a login, so they must be reachable publicly. For private images, send them as base64 or upload them to a public key-value store.

**Is my image data stored?** Base64 data is never echoed into results or logs, and failed pairs drop their payload. The diff overlay is the only image the Actor stores, in the run's key-value store.

**What happens when the run's time limit is close?** Pairs that cannot finish in the remaining time are not started and are reported with a `time_limit` error instead of being cut off half way. Results already produced are kept and only compared pairs are charged.

**What do I pay for failed pairs?** Nothing. Only successfully compared pairs are charged.

### Related Actors

- [Website Screenshot API](https://apify.com/bite-sized-insights/website-screenshot-api) - Screenshots as visual records of pages.
- [Image Compressor & Resizer](https://apify.com/bite-sized-insights/bulk-image-converter-compressor-and-resizer) - Batch-optimize image libraries.
- [convert web pages to PDF](https://apify.com/bite-sized-insights/url-to-pdf-converter) - Print-ready PDFs from any URL or HTML.

### Support

Found a bug or need a feature? Open an issue in the Issues tab of this Actor.

# Actor input Schema

## `pairs` (type: `array`):

Per pair: baseline, candidate (URL, data URI or base64, 25 MB max each), optional label.

## `similarityThreshold` (type: `number`):

A pair passes when its SSIM score (0 to 1) is at least this value.

## `maxDiffPercent` (type: `number`):

Optional. A pair also fails when more than this percentage of pixels changed.

## `pixelTolerance` (type: `integer`):

Largest per-channel colour difference (0 to 255) still treated as unchanged.

## `resizeMode` (type: `string`):

Scale the candidate to the baseline size, or report an error when the sizes differ.

## `maxDimension` (type: `integer`):

Larger images are scaled down to fit. Reported regions stay in baseline pixels.

## `normalize` (type: `string`):

Optionally ignore colour or contrast differences by normalizing both images first.

## `ignoreRegions` (type: `array`):

Areas in baseline pixels ({x, y, width, height}), such as ads, applied to every pair.

## `createDiffImage` (type: `boolean`):

Store a PNG overlay marking changed pixels and regions, and return its public link.

## Actor input object example

```json
{
  "pairs": [
    {
      "baseline": "https://httpbin.org/image/png",
      "candidate": "https://httpbin.org/image/jpeg",
      "label": "Sample images"
    }
  ],
  "similarityThreshold": 0.98,
  "pixelTolerance": 10,
  "resizeMode": "candidate-to-baseline",
  "maxDimension": 1600,
  "normalize": "none",
  "ignoreRegions": [],
  "createDiffImage": true
}
```

# Actor output Schema

## `results` (type: `string`):

Per-pair similarity, pixel diff, changed regions, pass/fail verdict and diff image link

## `diffImages` (type: `string`):

Key-value store holding the diff overlay PNGs (diff-00001.png, ...)

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "pairs": [
        {
            "baseline": "https://httpbin.org/image/png",
            "candidate": "https://httpbin.org/image/jpeg",
            "label": "Sample images"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("bite-sized-insights/visual-diff-api").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "pairs": [{
            "baseline": "https://httpbin.org/image/png",
            "candidate": "https://httpbin.org/image/jpeg",
            "label": "Sample images",
        }] }

# Run the Actor and wait for it to finish
run = client.actor("bite-sized-insights/visual-diff-api").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "pairs": [
    {
      "baseline": "https://httpbin.org/image/png",
      "candidate": "https://httpbin.org/image/jpeg",
      "label": "Sample images"
    }
  ]
}' |
apify call bite-sized-insights/visual-diff-api --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,bite-sized-insights/visual-diff-api"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/wdm83jKxrIp1ndxgi/builds/OusuHUfjHtgRYPufN/openapi.json
