Saturday, December 5, 2026

Run a Local LLM with Spring AI and Ollama: A Java REST Example

Want to call a language model from a Java application without sending each prompt to a hosted model API? In this walkthrough, we will run Qwen 2.5 locally with Ollama, connect it to Spring AI, and expose a small REST endpoint. The same pattern is a starting point for the TrainingHub project used in the Spring AI course.

What you will build: a Spring Boot endpoint that accepts a message, passes it through ChatClient, and returns the model response as JSON.

Request flow: REST client → Spring Boot controller → Spring AI ChatClient → Ollama → local model → JSON response.

1. Prerequisites

  • Java 21 and Maven (or the Maven wrapper generated by Spring Initializr).
  • Ollama installed and running on the same machine.
  • An internet connection and enough disk space for the first model and dependency downloads.

The prompts in this example go to the local Ollama server at localhost. Installing software and downloading the model and Maven dependencies require network access. Local inference does not by itself guarantee privacy: consider logs, other network calls, and how the application is deployed.

2. Download and check the model

Open a terminal and run:

ollama pull qwen2.5:1.5b
ollama list

Check that qwen2.5:1.5b appears in the list. You can also try ollama run qwen2.5:1.5b to chat in the terminal. If Ollama is installed but its server is not running, start the Ollama application; on systems where it is not already running as a service, ollama serve starts the server.

3. Create the Spring Boot project

Open Spring Initializr and generate a Maven project using Java 21, package name com.example.localai and Spring Boot 4.2.0. Download and unzip it, then open the extracted folder containing pom.xml in IntelliJ IDEA as a Maven project. Set the project JDK to 21. Keep the generated application class and Maven wrapper files.

Replace the entire contents of the generated pom.xml with the complete file below, then reload Maven in IntelliJ. Do not paste it inside the existing file: XML can contain only one properties section here. The first dependency enables REST controllers; the second connects Spring AI to Ollama. The BOM manages Spring AI dependency versions.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.2.0</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>localai</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>21</java.version>
        <spring-ai.version>2.1.0</spring-ai.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-model-ollama</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

The example combines Spring Boot 4.2.0 and Spring AI 2.1.0, as recommended by the Spring AI 2.1 release announcement. Other combinations require checking their compatibility.

4. Configure the local model

Add the following to src/main/resources/application.properties:

spring.ai.model.chat=ollama
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.model=qwen2.5:1.5b
spring.ai.ollama.chat.temperature=0.0

The base URL points to the Ollama server, and the model name must match the one downloaded in step 2. Temperature influences sampling; even with a low value, model responses can vary. Some older Spring AI examples use spring.ai.ollama.chat.options.model; consult the documentation for your exact version. If you run Ollama in Docker or from another host, use the address and exposed port reachable from the application.

5. Add a REST controller

Place the class below under the package containing your Spring Boot application, for example src/main/java/com/example/localai/LocalChatController.java:

package com.example.localai;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/chat")
public class LocalChatController {
    private final ChatClient chatClient;

    public LocalChatController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    @PostMapping
    public ChatResponse ask(@RequestBody ChatRequest request) {
        String answer = chatClient.prompt()
                .user(request.message())
                .call()
                .content();
        return new ChatResponse(answer);
    }

    public record ChatRequest(String message) {}
    public record ChatResponse(String answer) {}
}

Spring injects the configured ChatClient.Builder. The controller places the incoming message in the prompt, call() sends it synchronously via Spring AI to Ollama, and content() extracts the text. The response record is serialized to JSON. This deliberately small example omits input validation, authentication and production error handling.

6. Build, run and test

Open a terminal in the extracted project root, the directory containing pom.xml. With the generated Maven wrapper on Windows PowerShell, build and run:

.\mvnw.cmd clean package -DskipTests
java -jar target/localai-0.0.1-SNAPSHOT.jar

On macOS or Linux, use ./mvnw clean package -DskipTests for the first command. If you have Maven installed, mvn clean package -DskipTests works too. The wrapper may need network access to download Maven on its first run. This demonstration skips tests; it does not claim that a test suite passed. The verification below used an installed Maven, not a separately tested wrapper download.

When the application has started and Ollama is running, open a second terminal and send a request. For PowerShell:

$body = @{ message = 'Explain what Spring AI does in one sentence.' } | ConvertTo-Json
Invoke-RestMethod -Uri 'http://localhost:8080/api/chat' -Method Post `
    -ContentType 'application/json' -Body $body

For a Unix-style shell:

curl -X POST http://localhost:8080/api/chat -H 'Content-Type: application/json' -d '{"message":"Explain what Spring AI does in one sentence."}'

Observed result: I compiled the example with Maven 3.9.11, Java 21.0.13.1, Spring Boot 4.2.0 and Spring AI 2.1.0, using a separate initially empty Maven repository. The Qwen model was already available locally and was not downloaded again for this check. mvn clean package -DskipTests finished with BUILD SUCCESS. I started the resulting JAR and sent the PowerShell request above to local Ollama 0.11.10 and qwen2.5:1.5b; the response was:

{"answer":"Spring AI is an open-source framework for building and deploying machine learning models using the Spring ecosystem."}

This is a real model response, not an authoritative definition: it oversimplifies Spring AI. The framework integrates AI capabilities with Spring applications. Responses can vary; the first call may take longer while the model loads. In this environment, Maven initially reported a certificate trust error; using the Windows trusted root store resolved it without disabling TLS verification. This adjustment is environment-specific and is not required for every installation.

Troubleshooting

  • Connection refused: confirm Ollama is running and that the configured host and port are reachable from the Spring application.
  • Model not found: compare the name in ollama list with the model property and pull the matching tag.
  • Download fails with an x509 certificate error: check the machine or corporate proxy trust configuration with your administrator. Do not disable certificate verification.
  • Slow response or memory pressure: start with a small model such as this one and check available RAM; model quality and speed depend on hardware.
  • Wrong setting for your version: compare the properties with the Spring AI reference for the exact release used by your project.

Where to go next

This example makes one local model call. To build a useful assistant, you can add conversation context, retrieval from your own documents, Java tools and approval before changes to business data. The Spring AI with Java course explores these ideas through the TrainingHub project, including RAG, MCP and a Thymeleaf interface.

References: Spring AI Ollama integration · ChatClient reference · Qwen 2.5 model library.

Thursday, December 3, 2026

New course: Build AI applications with Java and Spring AI

How can a Java application answer a question using current business information, use documents as evidence and propose a change that a person can approve?

My new course, Spring AI with Java: RAG, Tools, Agents and MCP, is now available on Udemy. It follows one practical application, TrainingHub, from an initial model request to an assistant that works with documents, application tools and a database.

Watch the local LLM chat in action

In this 2-minute TrainingHub demo, a local model running in Ollama remembers a name from the previous message. The app then uses RAG to find the relevant policy excerpt and shows it alongside the answer. Finally, a proposed schedule change only reaches PostgreSQL after a person approves it.

Watch the full demo on YouTube · Explore the Spring AI course on Udemy

What you will build

TrainingHub is a training assistant that can retrieve course information, answer policy questions and propose a schedule change. The application checks that a person is authorized to approve a proposal before it applies the change to PostgreSQL.

A language model does not need to memorize the course schedule or the policy documents. The application provides the relevant information through Java tools and retrieval. The course shows how those pieces fit together and how to inspect what was returned.

What the course covers

  • Connect a Spring Boot application to a local language model with Spring AI ChatClient.
  • Work with prompts, structured responses, streaming and conversation memory.
  • Follow a tool call through its arguments, Java execution and result.
  • Build a RAG flow with embeddings, PostgreSQL and pgvector; explore Spring AI PgVectorStore and check the sources behind an answer.
  • Explore agent workflows, human approval and MCP clients and servers.
  • Test business rules and RAG behavior, and inspect latency, timeouts and retries.

The English-language course includes demonstrations in IntelliJ IDEA, downloadable projects and exercises. It is intended for developers who already know basic Java, Spring Boot and REST. Examples use Java 21, Docker, PostgreSQL and local Ollama models. Model responses can vary; production systems require additional security and reliability work.

Explore the course

Explore the course on Udemy with the promotional coupon

Watch the short introduction on YouTube, the Instagram Reel, or the full course preview.

Disclosure: this post promotes my course. The course and video include AI-generated narration.

Sunday, November 29, 2026

UNION vs UNION ALL vs EXCEPT: Why Does Your SQL Return a Different Number of Rows?

You combine two SQL query results. One version returns eight rows; another returns four. Nothing is missing from the database: changing UNION ALL to UNION changed how duplicate rows are handled.

This guide shows how PostgreSQL combines and compares results, using overlapping circles and a runnable example. You will also see where Oracle's MINUS fits and why reversing the inputs changes an EXCEPT result.

Watch the tutorial

See the diagrams and examples explained step by step in the full YouTube tutorial. For a quick comparison, watch the UNION vs UNION ALL Short.

What you need

Use PostgreSQL and a SQL client such as the pgAdmin Query Tool. Each SQL block is self-contained: copy and execute a complete block at a time. WITH names the two temporary query results for that statement; VALUES supplies the sample rows. No persistent tables are created or changed.

The examples were executed against PostgreSQL 17.5 through PGlite, an in-memory WebAssembly build of PostgreSQL. Results are presented in sorted order because the queries end with ORDER BY. Oracle behavior below is based on its documentation; it was not tested on an Oracle server.

The two inputs

Our first result, A, contains four one-column rows: 1, 1, 2, NULL. The second result, B, also has four rows: 1, 3, NULL, NULL. A contains two copies of 1; B contains two NULL rows.

In the diagrams, the left-only region contains 2, the overlapping region contains 1 and NULL, and the right-only region contains 3. The circles show whether a value occurs on each side; they do not show the number of copies. The rows next to the diagram make those copies visible.

UNION ALL: keep every rowA21NULLB3A: 1, 1, 2, NULLB: 1, 3, NULL, NULLResult:1 · 1 · 1 · 2 · 3 · NULL · NULL · NULL8 rows: 1 appears 3 times; NULL appears 3 times.Circles show distinct values, not copy counts.Without ORDER BY, row order is not guaranteed.
Both circles are included; the result shows every copy.

UNION ALL: keep every row

WITH a(value) AS (VALUES (1), (1), (2), (NULL::integer)),
     b(value) AS (VALUES (1), (3), (NULL::integer), (NULL::integer))
SELECT value FROM a
UNION ALL
SELECT value FROM b
ORDER BY value NULLS LAST;

Result: 1, 1, 1, 2, 3, NULL, NULL, NULL — eight rows. UNION ALL preserves all four rows from A and all four from B. It does not remove repeated rows, whether those repetitions were already in one input or occur across both inputs.

UNION: remove duplicate result rows

WITH a(value) AS (VALUES (1), (1), (2), (NULL::integer)),
     b(value) AS (VALUES (1), (3), (NULL::integer), (NULL::integer))
SELECT value FROM a
UNION
SELECT value FROM b
ORDER BY value NULLS LAST;

Result: 1, 2, 3, NULL — four rows. All values present in either input remain, but UNION removes duplicate result rows. That's why the shaded circle regions are conceptually the same as for UNION ALL, even though the number of returned rows differs.

In this example a row has one column. With multiple selected columns, duplicate elimination compares the whole selected row. Two rows with the same customer ID and different course names are not duplicate result rows.

EXCEPT: rows in the first result but not the second

WITH a(value) AS (VALUES (1), (1), (2), (NULL::integer)),
     b(value) AS (VALUES (1), (3), (NULL::integer), (NULL::integer))
SELECT value FROM a
EXCEPT
SELECT value FROM b
ORDER BY value NULLS LAST;

Result: 2. 1 and NULL also occur in B, so they are excluded; 3 occurs only in B, so it was never a candidate from A. Plain EXCEPT returns distinct result rows.

A EXCEPT B: distinct differenceA21NULLB3A: 1, 1, 2, NULLB: 1, 3, NULL, NULLResult:21 and NULL occur in both and are excluded.Circles show distinct values, not copy counts.Without ORDER BY, row order is not guaranteed.
The highlighted left region remains; duplicates are removed.

Order matters

Switch the SELECT statements and the question changes from “what is in A but not B?” to “what is in B but not A?”

WITH a(value) AS (VALUES (1), (1), (2), (NULL::integer)),
     b(value) AS (VALUES (1), (3), (NULL::integer), (NULL::integer))
SELECT value FROM b
EXCEPT
SELECT value FROM a
ORDER BY value NULLS LAST;

Result: 3. A EXCEPT B and B EXCEPT A generally answer different questions.

EXCEPT ALL: subtract copies

PostgreSQL also supports EXCEPT ALL:

WITH a(value) AS (VALUES (1), (1), (2), (NULL::integer)),
     b(value) AS (VALUES (1), (3), (NULL::integer), (NULL::integer))
SELECT value FROM a
EXCEPT ALL
SELECT value FROM b
ORDER BY value NULLS LAST;

Result: 1, 2. For each distinct row, subtract the number of copies in B from the number in A, without going below zero. A contains two copies of 1 and B contains one, so one remains. A's single 2 remains; its single NULL is matched by a NULL in B and does not remain. The extra NULL in B does not produce a negative number of rows.

This is why a simple “A-only” shaded circle is insufficient for EXCEPT ALL: 1 appears in both input circles, yet one copy remains in the output.

A EXCEPT ALL B: subtract copiesA21NULLB3A: 1, 1, 2, NULLB: 1, 3, NULL, NULLResult:1 · 2A has 1 NULL; B has 2: zero NULLs remain.Circles show distinct values, not copy counts.Without ORDER BY, row order is not guaranteed.
The shared 1 still has one copy left: 2 copies minus 1 copy.

What about NULL?

In these set operations, PostgreSQL treats NULLs as matching for duplicate elimination and matching rows. Thus UNION shows one NULL here, while EXCEPT removes A's NULL because B contains one too. This does not mean the predicate NULL = NULL evaluates to true in a WHERE clause: SQL uses three-valued logic for that comparison.

PostgreSQL EXCEPT and Oracle MINUS

If you use Oracle, MINUS is the familiar operator for the distinct difference. In PostgreSQL, use EXCEPT; PostgreSQL does not use MINUS as a set operator. Oracle 19c documents MINUS, while Oracle Database 26 also documents EXCEPT as a synonym. Check your database version and its documentation when moving SQL between engines; the CTE and cast syntax in the examples above is PostgreSQL syntax.

Three practical rules

  1. Same number of columns: both input queries must return the same number of columns, with compatible types in corresponding positions.
  2. Whole rows matter: UNION and EXCEPT compare all columns in the selected row, not an individual column unless it is the only selected column.
  3. Order is not automatic: if result order matters, use an appropriate final ORDER BY. SQL does not promise that A's rows will appear before B's just because the query uses UNION ALL.

A quick exercise

Before running the query, predict the result of B EXCEPT ALL A using the same two inputs. Then swap the two SELECT statements in the EXCEPT ALL example. Remember to subtract copies for each row separately.

Show the expected answer

The expected result is 3, NULL: B has one 3 that is absent from A, and two NULLs compared with A's one NULL, leaving one copy. B's one 1 is matched by A's copies.

Continue learning PostgreSQL

For more hands-on SQL and PostgreSQL examples, explore my Practical SQL with PostgreSQL course on Udemy. This is a referral link to my course.

Official references

Friday, November 27, 2026

How PostgreSQL Triggers Track Changes: OLD, NEW and a Practical Example

An application runs one UPDATE. The status changes, and PostgreSQL records the old and new values in a second table—without a separate audit INSERT from the application. How does the database know what to do?

In this hands-on example, you will build two PostgreSQL triggers, see the actual results, and find out what happens when a transaction is rolled back. The example uses fictional data in temporary tables and does not change TrainingHub.

What is a trigger?

A trigger connects an event on a database object to a function that PostgreSQL runs automatically. Our event is an UPDATE on a table. The trigger definition says when and for which rows the function runs; the trigger function contains what to do. Creating the function or trigger does not itself update a row.

We will use a BEFORE UPDATE trigger to normalize the proposed status and an AFTER UPDATE trigger to record a change. Both are FOR EACH ROW: PostgreSQL considers each affected row separately. The WHEN condition on the second trigger restricts it to rows whose status actually differs. See the PostgreSQL trigger overview.

Before you begin

You need PostgreSQL and a SQL client such as pgAdmin's Query Tool or psql, permission to create temporary tables and functions, and basic familiarity with SELECT and UPDATE. This example was executed with psql against PostgreSQL 17.8; pgAdmin display and results can differ. Open one disposable learning session and run the blocks in order on the same connection. Temporary objects disappear when that session ends. The statements write to the temporary tables; they do not change TrainingHub.

In pgAdmin, select a block and use Execute/Run. If your client displays only the last result from multiple statements, run the statements individually to see each result. Starting again? Open a new connection and rerun setup; creating the same objects twice in the same session causes a name conflict.

1. Create the sample tables

CREATE TEMP TABLE demo_enrollments (
    enrollment_id integer PRIMARY KEY,
    status text NOT NULL
);

CREATE TEMP TABLE demo_status_audit (
    enrollment_id integer NOT NULL,
    old_status text NOT NULL,
    new_status text NOT NULL
);

INSERT INTO demo_enrollments VALUES (1, 'active');

demo_enrollments holds one enrollment. demo_status_audit starts empty and will hold the before-and-after values. CREATE TEMP TABLE makes these session-local tables. We deliberately omit timestamps and user identity to keep the example focused.

2. Define a BEFORE trigger function

CREATE FUNCTION pg_temp.normalize_status() RETURNS trigger
LANGUAGE plpgsql AS $function$
BEGIN
    NEW.status := lower(trim(NEW.status));
    RETURN NEW;
END;
$function$;

CREATE FUNCTION gives the routine a name; pg_temp places it in the session's temporary schema. The empty parentheses mean no ordinary function parameters. RETURNS trigger identifies this as a trigger function, and LANGUAGE plpgsql chooses the procedural language. Matching $function$ tags surround the function body; the tag is a delimiter, not a variable.

For this row-level update, NEW represents the proposed new row. trim removes surrounding spaces, lower makes letters lowercase, and := assigns the result to NEW.status. RETURN NEW passes the modified row onward. This return value matters for a row-level BEFORE trigger: returning NULL instead would skip that row's operation. The exact return rules depend on trigger timing and event; see PL/pgSQL trigger functions.

3. Attach the BEFORE trigger

CREATE TRIGGER normalize_enrollment_status
BEFORE UPDATE ON demo_enrollments
FOR EACH ROW
EXECUTE FUNCTION pg_temp.normalize_status();

The trigger is named normalize_enrollment_status; it runs before updates to demo_enrollments, once for each affected row. EXECUTE FUNCTION identifies the trigger function. This example uses a PostgreSQL function returning trigger, not a procedure invoked with CALL.

4. Define and attach an AFTER trigger

CREATE FUNCTION pg_temp.record_status_change() RETURNS trigger
LANGUAGE plpgsql AS $function$
BEGIN
    INSERT INTO pg_temp.demo_status_audit
        (enrollment_id, old_status, new_status)
    VALUES (NEW.enrollment_id, OLD.status, NEW.status);
    RETURN NULL;
END;
$function$;

In this row-level UPDATE, OLD.status is the value before the update and NEW.status is the new value after our BEFORE normalization. The function inserts both into the audit table. PostgreSQL ignores the return value of an AFTER row trigger function, so this example uses RETURN NULL; it does not cancel the update.

CREATE TRIGGER audit_enrollment_status
AFTER UPDATE ON demo_enrollments
FOR EACH ROW
WHEN (OLD.status IS DISTINCT FROM NEW.status)
EXECUTE FUNCTION pg_temp.record_status_change();

AFTER UPDATE associates the function with completed updates. This ordinary AFTER row trigger runs at the end of the statement, still within the transaction. Its WHEN condition allows a log entry only when the old and new values differ. IS DISTINCT FROM also gives a definite comparison for NULL values, though both statuses in our sample tables are NOT NULL. Merely naming a column in UPDATE OF status is not the same as testing whether its value changed. See CREATE TRIGGER.

5. Update and inspect the result

UPDATE demo_enrollments
SET status = '  COMPLETED  '
WHERE enrollment_id = 1;

SELECT * FROM demo_enrollments;
SELECT * FROM demo_status_audit;

In the tested run, the first result is 1 | completed. The audit result is 1 | active | completed. The BEFORE function trimmed and lowercased the proposed value; then the AFTER function recorded the transition. The SQL statement did not explicitly insert into the audit table.

What if we write the same status again?

UPDATE demo_enrollments
SET status = 'completed'
WHERE enrollment_id = 1;

SELECT count(*) AS audit_rows_after_same_status
FROM demo_status_audit;

The tested result is 1. The UPDATE still affects the matching row, but the AFTER trigger's condition is false for the unchanged normalized status, so no additional audit row is inserted.

6. What does ROLLBACK do?

Run setup and the previous blocks first, then execute these statements on the same connection. Use normal autocommit for the earlier blocks so that the sample objects and first change are established before the explicit transaction.

BEGIN;
UPDATE demo_enrollments SET status = 'cancelled' WHERE enrollment_id = 1;
SELECT status FROM demo_enrollments WHERE enrollment_id = 1;
SELECT count(*) AS audit_rows_before_rollback FROM demo_status_audit;
ROLLBACK;

SELECT * FROM demo_enrollments;
SELECT * FROM demo_status_audit;

Before ROLLBACK, the status is cancelled and the audit table has 2 rows in this session. After rollback, the status is completed and only 1 | active | completed remains in the audit table. The trigger and the statement run in the same transaction, so the rollback reverses both changes from this transaction. This also means a trigger error can cause the triggering statement to fail. See the PostgreSQL documentation on trigger behavior.

BEFORE, AFTER and scope: what to remember

  • BEFORE row: can inspect or modify NEW for an INSERT or UPDATE; the appropriate returned row controls what happens next.
  • AFTER row: can react to the completed operation. This example records a status transition; it does not change the stored row by returning a different value.
  • ROW versus STATEMENT: a row trigger is considered for each affected row; an applicable statement trigger is considered once per statement, including when zero rows are affected. WHEN conditions can restrict both.
  • OLD and NEW: for an UPDATE row trigger both are available; their availability differs for INSERT, DELETE and statement triggers.

This small temporary audit table is a teaching example, not a complete security audit. It does not identify a person, prevent authorized changes to audit records, retain history after the session ends, or capture all database operations. Real systems need deliberate permissions, retention, monitoring, performance testing and a trustworthy identity strategy. Triggers add work and can hide side effects, so document them and measure behavior in your own workload.

Try it yourself

After setup in a fresh session, change the first status to ' ACTIVE '. Predict the normalized value and number of audit rows, then run the update and query both tables. Why does the condition avoid a new record? Next change it to 'completed' and check again.

For more hands-on SQL and PostgreSQL, explore Practical SQL with PostgreSQL: From Queries to Real Projects. This is the instructor's referral link. The example in this article is free and runs independently of the course.

Thursday, November 26, 2026

Why Does SQL BETWEEN Miss Orders on the Last Day?

Your report asks for orders from November 29 through November 30. The query runs without an error, but an order from November 30 at 13:45 is missing. Why?

In this tutorial we reproduce the boundary problem in PostgreSQL, inspect the exact result and build a date range that includes the entire last calendar day. The examples use fictional data and self-contained SELECT statements; no table is created or changed. Run each complete block in pgAdmin's Query Tool or another PostgreSQL client. The recorded execution used PostgreSQL 18.6 with psql.

Five orders around the boundary

We want orders on November 29 and November 30, including both full calendar days. The timestamps below are explicitly timestamp without time zone; for now, treat them as local date-and-time values with no time-zone conversion.

order_idplaced_atInclude?
12026-11-29 23:59:59yes
22026-11-30 00:00:00yes
32026-11-30 13:45:00yes
42026-11-30 23:59:59.999999yes
52026-12-01 00:00:00no

The query that misses part of the day

Here are explicit timestamp bounds, each at midnight:

WITH orders(order_id, placed_at) AS (
    VALUES (1, TIMESTAMP '2026-11-29 23:59:59'),
           (2, TIMESTAMP '2026-11-30 00:00:00'),
           (3, TIMESTAMP '2026-11-30 13:45:00'),
           (4, TIMESTAMP '2026-11-30 23:59:59.999999'),
           (5, TIMESTAMP '2026-12-01 00:00:00')
)
SELECT order_id, placed_at
FROM orders
WHERE placed_at BETWEEN TIMESTAMP '2026-11-29 00:00:00'
                    AND TIMESTAMP '2026-11-30 00:00:00'
ORDER BY order_id;

The result contains only orders 1 and 2. BETWEEN includes both endpoints: order 2 is exactly equal to the upper boundary and is included. Order 3 is later than 2026-11-30 00:00:00, so it is excluded along with order 4. PostgreSQL is applying the specified range correctly; it has not interpreted the upper boundary as the end of November 30. See PostgreSQL's comparison predicates.

An equivalent condition here is placed_at >= TIMESTAMP '2026-11-29 00:00:00' AND placed_at <= TIMESTAMP '2026-11-30 00:00:00'. The inclusive upper comparison is the key detail.

Include the whole final day

Use the start of the first day, inclusive, and the start of the following day, exclusive:

WITH orders(order_id, placed_at) AS (
    VALUES (1, TIMESTAMP '2026-11-29 23:59:59'),
           (2, TIMESTAMP '2026-11-30 00:00:00'),
           (3, TIMESTAMP '2026-11-30 13:45:00'),
           (4, TIMESTAMP '2026-11-30 23:59:59.999999'),
           (5, TIMESTAMP '2026-12-01 00:00:00')
)
SELECT order_id, placed_at
FROM orders
WHERE placed_at >= TIMESTAMP '2026-11-29 00:00:00'
  AND placed_at <  TIMESTAMP '2026-12-01 00:00:00'
ORDER BY order_id;

This half-open interval returns orders 1, 2, 3 and 4. It includes midnight at the start of November 30 and the last sample before December 1, while order 5, exactly at the next midnight, is excluded. For adjacent reporting periods, the same boundary can be the exclusive end of one period and the inclusive start of the next.

Why not BETWEEN and the next midnight?

Try a seemingly small change:

WITH orders(order_id, placed_at) AS (
    VALUES (1, TIMESTAMP '2026-11-29 23:59:59'),
           (2, TIMESTAMP '2026-11-30 00:00:00'),
           (3, TIMESTAMP '2026-11-30 13:45:00'),
           (4, TIMESTAMP '2026-11-30 23:59:59.999999'),
           (5, TIMESTAMP '2026-12-01 00:00:00')
)
SELECT order_id, placed_at
FROM orders
WHERE placed_at BETWEEN TIMESTAMP '2026-11-29 00:00:00'
                    AND TIMESTAMP '2026-12-01 00:00:00'
ORDER BY order_id;

This returns all five orders. Because BETWEEN includes the upper endpoint, it also includes order 5 exactly at December 1 midnight. This might be correct for a different business question, but it is outside our two-day calendar report.

Why not hard-code 23:59:59?

23:59:59 excludes order 4, whose time is 23:59:59.999999. Using a final representable fraction also couples the condition to the precision of the data type. The next-day exclusive boundary is clearer and does not require guessing a last fractional instant. PostgreSQL's date/time types describe timestamp precision.

What changes with time zones?

These examples use timestamp without time zone and do not demonstrate UTC conversions. If your actual column is timestamptz and the business rule concerns a local calendar day, determine both local-midnight boundaries in the intended named time zone and convert them appropriately before comparing instants. Daylight-saving transitions mean local days need not always be 24 hours. Avoid depending on the database session's default time zone without an explicit rule. PostgreSQL documents date/time comparisons and time zones. Test the exact rules and boundaries in your own environment.

The example is a correctness demonstration, not a performance benchmark. A range predicate can be useful with suitable indexes, but the chosen execution plan depends on the query, data and settings; use EXPLAIN on a representative workload before drawing performance conclusions.

Try it yourself

Add a sixth order at 2026-11-29 00:00:00 and predict whether each query returns it. Then add one at 2026-12-01 00:00:00.000001. Predict the results again and run the blocks. What happens at each inclusive or exclusive boundary?

For more hands-on SQL and PostgreSQL practice, explore Practical SQL with PostgreSQL: From Queries to Real Projects. This is the instructor's referral link. These examples are free and run independently of the course.

Max Pooling in CNNs: A Step-by-Step Python Example

How can a neural network make a feature map smaller without simply throwing away entire rows and columns? One option is max pooling: take a small window of values, keep its largest value, and repeat across the map.

In this tutorial, you will shrink a 4×4 map to 2×2 by hand and reproduce each step in Python. The numbers are a small, hand-written teaching example—not activations recorded from a trained model. We use a 2×2 window, a stride of 2 and no padding throughout.

Watch the step-by-step max pooling video tutorial or the animated 25-second Short. To see how a filter creates a feature map before this step, watch my CNN filter animation.

What is max pooling?

A feature map is a grid of values produced by a network layer. Max pooling looks at a local window of that grid and returns the largest value in the window. It then moves the window and repeats. Unlike a convolutional filter, a max-pooling window has no weights to learn: it applies the chosen maximum rule.

Window size says how many neighboring values we inspect. Stride says how far we move the window between positions. With a 2×2 window and stride 2, the windows in this example do not overlap. The TensorFlow MaxPool2D documentation describes window, stride and padding options.

Start with a 4×4 feature map

Here is our input. Treat each number as a sample feature-map value:

1  3  |  2  4
5  6  |  1  0
------+------
7  2  |  8  3
4  1  |  6  9

The lines divide the map into four 2×2 windows. Place a window in the upper-left corner. It contains 1, 3, 5, 6, so its maximum is 6. That becomes the upper-left value in the output.

Move the window and build the result

A stride of 2 moves the window two columns to the right. After that, we move two rows down and repeat. Here are all four calculations:

  • Upper left: max(1, 3, 5, 6) = 6
  • Upper right: max(2, 4, 1, 0) = 4
  • Lower left: max(7, 2, 4, 1) = 7
  • Lower right: max(8, 3, 6, 9) = 9

Put each maximum in the corresponding output position:

6  4
7  9

The input contains 16 values; the output contains 4. We reduced both the height and width from 4 to 2. The largest value from each window is retained, but the other values are lost. Knowing the four maxima alone does not let us reconstruct the original 4×4 map.

Calculate max pooling in Python

You need Python and NumPy. If NumPy is not installed in your selected environment, run python -m pip install numpy. Save the code as max_pooling_example.py, then run python max_pooling_example.py. It needs no model weights, image file or GPU.

import numpy as np


def max_pool_2x2_stride2(feature_map):
    """Pool complete 2x2 windows with stride 2 and no padding."""
    feature_map = np.asarray(feature_map)
    if feature_map.ndim != 2 or min(feature_map.shape) < 2:
        raise ValueError("Provide a two-dimensional array of at least 2x2.")
    height, width = feature_map.shape
    pooled = np.empty((height // 2, width // 2), dtype=feature_map.dtype)
    for output_row, row in enumerate(range(0, height - 1, 2)):
        for output_col, col in enumerate(range(0, width - 1, 2)):
            window = feature_map[row : row + 2, col : col + 2]
            pooled[output_row, output_col] = np.max(window)
    return pooled


feature_map = np.array([
    [1, 3, 2, 4],
    [5, 6, 1, 0],
    [7, 2, 8, 3],
    [4, 1, 6, 9],
])
print("Input feature map (4x4):")
print(feature_map)
for row in range(0, feature_map.shape[0] - 1, 2):
    for col in range(0, feature_map.shape[1] - 1, 2):
        window = feature_map[row : row + 2, col : col + 2]
        print(f"Window at row {row}, column {col}:\n{window}")
        print(f"Maximum = {np.max(window)}")
print("Max-pooled feature map (2x2):")
print(max_pool_2x2_stride2(feature_map))

The four printed maxima are 6, 4, 7, 9. The final output is:

[[6 4]
 [7 9]]

The slices select each window, and np.max(window) returns its largest value. The function accepts a two-dimensional array of at least 2×2. It uses complete 2×2 windows with stride 2; incomplete windows on the right or bottom are skipped, and no padding is added.

Why can a smaller map be useful?

Reducing spatial dimensions means subsequent layers process fewer spatial positions, which can reduce computation and memory use. Keeping the largest response in each window can retain a strong local response, but it discards other values and their exact locations inside that window. Whether this helps depends on the task and model. Max pooling is one option; not every CNN uses it.

In a CNN with multiple channels, pooling generally operates separately on each feature-map channel. Our small example shows one 2D map, not a complete image-classification model.

Try it yourself

Change the lower-right value from 9 to 5 and predict the new output before running the script. Run the modified script to check your prediction. Only the lower-right output changes, from 9 to 8, because 8 becomes the maximum in that window.

Frequently asked questions

Does max pooling train a filter?
No. It chooses the maximum in each window. The window size and stride are configuration choices; this operation does not learn filter weights.

Is max pooling the same as average pooling?
No. Max pooling returns the largest value in each window; average pooling returns the average of its values.

Does the map always shrink by half?
No. This example halves each dimension because its input is 4×4 and uses a 2×2 window with stride 2 and no padding. Output size depends on the input, window, stride and padding.

Does the largest value always mean the most important part of the original image?
Not necessarily. Its interpretation depends on the feature map and model. Pooling preserves the largest value within each window, not a guaranteed explanation of a prediction.

Continue learning

See the Computer Vision course overview for more about the course and its practical projects. My English-language course Computer Vision: OpenCV, Machine Learning and YOLO includes CNN concepts and practical work. This is my instructor referral link.

Tuesday, November 24, 2026

Why Does SELECT Fail? PostgreSQL Procedures vs Functions

Watch the tutorial

Watch the full PostgreSQL procedures tutorial or the short introduction.

You created a database routine, but SELECT produces an error: “is a procedure.” What happened? In PostgreSQL, a procedure is invoked with CALL. A function can be invoked in an expression such as SELECT. Let’s reproduce the error, then build and call a procedure that completes a group of synthetic enrollments.

The goal is to understand the definition, inputs, body, returned output and observed data changes—not just memorize a keyword. This example was executed with psql against PostgreSQL 18.6. You may use pgAdmin’s Query Tool or another compatible PostgreSQL client; the walkthrough below has not been separately tested in every client.

Before you begin

Use a PostgreSQL database where your account can create temporary tables and define the demonstrated temporary routines. Use a disposable learning session. All sample rows are fictional and independent of TrainingHub. The procedure performs an UPDATE, but only on our temporary sample table; it does not change a TrainingHub table. Keep the same database connection open for the complete walkthrough: the temporary table and routines belong to that session. Closing the session removes them.

Run the setup once. To start over, open a new database session and rerun it; running CREATE TEMP TABLE twice in the same session will report that the table already exists. Execute the deliberate error separately, with normal autocommit enabled. If you deliberately use an explicit transaction, an error can leave it aborted until ROLLBACK, and if the setup is part of that transaction rollback can remove the setup too. In that case start a fresh session and run the setup again.

The sample: four enrollments

enrollment_idcourse_idstatus
1101active
2101active
3102active
4101completed

The task: mark the active enrollments of one course as completed, then report how many rows changed. For course 101, two active rows match. Row 4 is already completed, and course 102 must remain untouched.

Set up the table, procedure and function

Run this entire setup block in one session. We explain both definitions below before invoking them.

-- Run the setup and all later statements in the SAME database session.
-- Synthetic sample; the table and routines live in the current temporary schema.
CREATE TEMP TABLE demo_enrollments (
    enrollment_id integer PRIMARY KEY,
    course_id integer NOT NULL,
    status text NOT NULL
);

INSERT INTO demo_enrollments (enrollment_id, course_id, status)
VALUES (1, 101, 'active'), (2, 101, 'active'),
       (3, 102, 'active'), (4, 101, 'completed');

CREATE PROCEDURE pg_temp.complete_course(
    IN p_course_id integer,
    INOUT p_updated_count integer
)
LANGUAGE plpgsql
AS $procedure$
BEGIN
    UPDATE demo_enrollments
    SET status = 'completed'
    WHERE course_id = p_course_id AND status = 'active';
    GET DIAGNOSTICS p_updated_count = ROW_COUNT;
END;
$procedure$;

CREATE FUNCTION pg_temp.active_count(p_course_id integer)
RETURNS bigint
LANGUAGE sql
AS $function$
    SELECT count(*) FROM demo_enrollments
    WHERE course_id = p_course_id AND status = 'active';
$function$;

CREATE TEMP TABLE creates a session-local table, and INSERT populates the four synthetic rows. pg_temp refers to this session’s temporary schema; it keeps the two demonstration routines separate from permanent application routines.

Read the procedure definition

CREATE PROCEDURE pg_temp.complete_course defines a named procedure; creation does not run its body. The parameters in parentheses have names, modes and types:

  • IN p_course_id integer receives the course identifier, such as 101.
  • INOUT p_updated_count integer accepts an input value and exposes an output value. This procedure overwrites the supplied initial value with the count. In a SQL CALL, the output parameter appears in a result row; it is not a guarantee that every procedure returns a result set.

LANGUAGE plpgsql chooses PostgreSQL’s procedural language. The matching $procedure$ tags delimit the procedure body as a string; the word inside the matching dollar-quote tags is a label, not a variable or parameter. Inside the BEGIN ... END block, the UPDATE targets only rows of the supplied course whose current status is active. Immediately afterward, GET DIAGNOSTICS p_updated_count = ROW_COUNT assigns the number of rows affected by that SQL command to the output parameter. See the official CREATE PROCEDURE and PL/pgSQL diagnostics documentation.

Read the function definition

The second definition, CREATE FUNCTION pg_temp.active_count(p_course_id integer), accepts a course ID. Its RETURNS bigint specifies the return type. Its LANGUAGE sql body is delimited by matching $function$ tags and returns the count of that course’s active rows. This specific function reads the sample table; functions are not universally read-only, and their effects depend on their definitions.

Why does SELECT fail for the procedure?

Run this separate statement after setup in the same session:

-- Intentional error: a procedure is not called with SELECT.
SELECT pg_temp.complete_course(101, 0);

PostgreSQL 18.6 reports:

ERROR:  pg_temp.complete_course(integer, integer) is a procedure
HINT:  To call a procedure, use CALL.

That statement does not invoke the procedure body. Use CALL for this procedure. Use SELECT for the active_count function in this example. A procedure can have output parameters as our example does, and a function can return scalar or set results; avoid assuming that “procedure” simply means no result. See PostgreSQL’s CALL reference.

Execute, inspect and repeat

Still in the same session, run each statement in order. If your client displays only the last result of a multi-statement execution, execute the statements individually so you can inspect each result.

-- Run after 01_setup.sql in the SAME session. The routine is not read-only.
SELECT pg_temp.active_count(101) AS active_before;
CALL pg_temp.complete_course(101, 0);
SELECT enrollment_id, course_id, status FROM demo_enrollments ORDER BY enrollment_id;
SELECT pg_temp.active_count(101) AS active_after;
CALL pg_temp.complete_course(101, 0);
  1. SELECT pg_temp.active_count(101) AS active_before returns 2: enrollment IDs 1 and 2 are active for course 101.
  2. CALL pg_temp.complete_course(101, 0) passes 101 to the input and 0 as the initial value of the INOUT parameter. The body overwrites that second value, and the result row has p_updated_count = 2.
  3. The table query shows IDs 1, 2 and 4 as completed; ID 3 stays active because it belongs to course 102.
  4. Calling the function again through SELECT gives active_after = 0 for course 101.
  5. A second identical CALL reports 0 changed rows because there are no active course-101 rows left in this fixture. This is a consequence of the particular WHERE clause, not a general property of procedures.
enrollment_idcourse_idstatus after first CALL
1101completed
2101completed
3102active
4101completed

These are actual values from the stated PostgreSQL execution. Other input data will produce different counts. The 0 argument is required here because p_updated_count is INOUT; this body does not use its incoming value. When calling a procedure from inside PL/pgSQL, output parameters have additional assignment rules; this tutorial shows direct SQL calls.

Functions, procedures and transaction control

In PostgreSQL, direct invocation is a practical distinction: SELECT pg_temp.active_count(101) invokes our function, whereas CALL pg_temp.complete_course(101, 0) invokes our procedure. The difference is not that functions can never change data or that procedures can never return output.

There are also important transaction-control differences. A procedure can use transaction control only under supported call conditions; for example, when CALL executes inside an explicit transaction block, the called procedure cannot execute transaction-control statements. Our procedure contains no COMMIT or ROLLBACK. Consult the CALL notes before designing routines that manage transactions.

Try it yourself

In a fresh session, rerun the setup. Predict the return value and changed row before calling CALL pg_temp.complete_course(102, 0). Use SELECT pg_temp.active_count(102) and the table query to check. Then call the same procedure again and explain why its count changes. Avoid applying this synthetic code to real customer data without appropriate validation and authorization.

For guided practice in PostgreSQL, SQL, functions and procedures, explore Practical SQL with PostgreSQL: From Queries to Real Projects. This is the instructor’s referral link. The example in this article is free and runs independently of the course.

Sunday, November 22, 2026

Traffic Heatmap with Python and YOLO: Visualize Vehicle Activity

Watch the full video tutorial · Watch the Short

Where did vehicles appear most often in a traffic video? A heatmap can turn a few seconds of bounding boxes into a picture that changes as the video plays. In this tutorial, we build one with Python, YOLO and OpenCV, and explain exactly what the colours represent.

The demonstration uses an AI-generated traffic scene. It is a small educational example, not a real traffic survey or a test of production accuracy.

What does this heatmap measure?

We divide the 1280 × 720 video into a 32 × 18 grid of 40 × 40 pixel cells. For each frame, a cell receives one point if its centre lies inside at least one accepted vehicle bounding box. It receives zero otherwise. We add the points across the frames.

This is detected box presence over frames. It is not the number of cars, the speed of a car, or a measurement of actual road occupancy. If two boxes overlap a cell centre in the same frame, that cell still receives only one point. A slowly moving or stationary vehicle can contribute to the same cell across many frames.

The source clip contains 241 frames at 24 frames per second. To keep colours comparable throughout the demonstration, the display uses a fixed scale from zero to 241 frames rather than stretching the range separately for every image. At any time, a value of 24 would mean the cell centre was covered by an accepted box in 24 processed frames; with every source frame processed, that corresponds to about one second of detected box presence in the video. The value is still a model-derived observation, not a confirmed physical occupancy.

From video to map

  1. Read the traffic clip one frame at a time.
  2. Run YOLOv8n with a confidence threshold of 0.20 and accept COCO vehicle classes car, motorcycle, bus and truck. This demonstration uses ByteTrack results.
  3. For every grid cell, check whether its centre falls inside any accepted vehicle box in the current frame.
  4. Add at most one to each cell for that frame, map the accumulated values to colours and draw the result over the video.

A fixed camera matters: a cell represents a position in the image, so camera movement makes the same grid cell cover different parts of the scene. If the camera moves, stabilise or otherwise account for that motion before interpreting a spatial map.

The core update

The complete program below reads a local video, runs the selected local YOLO model and writes an annotated MP4, three example frames, the grid as a NumPy array and a JSON summary. For another video, use a fixed camera and a compatible trained model; results will differ. The clip used in the demonstration is not offered as a download here.

The tested Windows/CPU environment used ultralytics 8.4.24, opencv-python 4.13.0.92, numpy 2.3.5, lap 0.5.13 and a CPU installation of PyTorch 2.10.0. See the official PyTorch installation selector for a suitable installation command. In an activated Python environment, the other tested packages can be installed with:

python -m pip install ultralytics==8.4.24 opencv-python==4.13.0.92 numpy==2.3.5 lap==0.5.13

The first run needs the appropriate local model file and tracker dependencies installed; this example does not assume a network connection will fetch missing files. Package compatibility depends on the Python version and platform.

Save the code as heatmap.py. Put your own video and a compatible local yolov8n.pt in the working directory, then run:

python heatmap.py --video your_video.mp4 --model yolov8n.pt --out traffic_heatmap.mp4

In model mode the script selects CPU, a 0.20 confidence threshold, a 640-pixel inference size, vehicle classes 2, 3, 5 and 7, and bytetrack.yaml. The optional --cache mode is for a previously generated compatible frame-by-frame JSON cache, not for an arbitrary JSON file. When no model is available locally, supply the required weights through a legitimate source and review their terms before use.

The following example uses Ultralytics; review the Ultralytics licensing terms for your use. The demonstration code is provided under AGPL-3.0, Copyright ARTSCI - Author of the AI/ML/CV course materials. The AI-generated video is not included under that code license.

Show the complete Python script
"""Build a 40px-grid vehicle detection-presence heatmap (not a vehicle counter).

Examples:
  python heatmap.py --video input.mp4 --model yolov8n.pt --out result.mp4
  python heatmap.py --video input.mp4 --cache tracks_cache.json --out result.mp4

The cache option requires an identical source-file SHA-256; model mode performs
local inference. For reproducible model mode, use the versions in README.md.
"""
import argparse
import hashlib
import json
from pathlib import Path

import cv2
import numpy as np


def sha256(path):
    h = hashlib.sha256()
    with open(path, 'rb') as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b''):
            h.update(chunk)
    return h.hexdigest()


def presence(boxes, w, h, grid=40):
    """One boolean per cell, true if its center is in any detection box."""
    # An edge cell can be narrower than grid; its true center is halfway
    # between its starting coordinate and the clipped image edge.
    left = np.arange((w + grid - 1) // grid) * grid
    top = np.arange((h + grid - 1) // grid) * grid
    x = (left + np.minimum(left + grid, w)) / 2
    y = (top + np.minimum(top + grid, h)) / 2
    present = np.zeros((len(y), len(x)), dtype=bool)
    for x1, y1, x2, y2 in boxes:
        present |= ((y[:, None] >= y1) & (y[:, None] <= y2) &
                    (x[None, :] >= x1) & (x[None, :] <= x2))
    return present


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--video', required=True)
    mode = p.add_mutually_exclusive_group(required=True)
    mode.add_argument('--cache', help='frame-indexed detections cached for this exact file')
    mode.add_argument('--model', help='local Ultralytics YOLO .pt file')
    p.add_argument('--out', default='traffic_heatmap.mp4')
    p.add_argument('--grid', type=int, default=40)
    p.add_argument('--confidence', type=float, default=0.20)
    p.add_argument('--save-cache', help='save inference results as JSON')
    args = p.parse_args()
    if args.grid < 1 or not 0 <= args.confidence <= 1 or (args.cache and args.save_cache):
        p.error('--save-cache requires --model, not --cache' if args.cache and args.save_cache else 'grid must be positive, confidence must be between 0 and 1')
    cap = cv2.VideoCapture(args.video)
    if not cap.isOpened():
        raise RuntimeError('Could not open video')
    w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = float(cap.get(cv2.CAP_PROP_FPS))
    total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    if total < 1 or fps <= 0 or w % 2 or h % 2:
        raise ValueError('Video must have a known frame count, positive FPS, and even width and height; resize or pad odd dimensions first.')
    cache = None
    if args.cache:
        cache = json.loads(Path(args.cache).read_text(encoding='utf-8'))
        if cache['key']['source_sha256'] != sha256(args.video):
            raise ValueError('Cache source hash mismatch; rerun with --model')
        if len(cache['rows']) != total or any(row['frame'] != i for i, row in enumerate(cache['rows'])):
            raise ValueError('Cache frame count or order mismatch')
        if cache['key']['conf'] != args.confidence or cache['key']['classes'] != [2, 3, 5, 7]:
            raise ValueError('Cache parameters differ from expected settings')
        rows = cache['rows']
    else:
        if not Path(args.model).is_file():
            raise FileNotFoundError('Model must be an existing local file')
        from ultralytics import YOLO
        model = YOLO(args.model)
        rows = []
    out = cv2.VideoWriter(args.out, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
    if not out.isOpened():
        raise RuntimeError('Could not open video writer')
    heat = np.zeros(((h + args.grid - 1)//args.grid, (w + args.grid - 1)//args.grid), dtype=np.uint32)
    counts = []
    try:
        for frame_id in range(total):
            ok, frame = cap.read()
            if not ok:
                raise RuntimeError(f'Cannot decode frame {frame_id}/{total}')
            if cache is not None:
                detections = rows[frame_id]['detections']
                boxes = [d['xyxy'] for d in detections]
            else:
                result = model.track(frame, persist=True, conf=args.confidence, classes=[2,3,5,7],
                                     imgsz=640, tracker='bytetrack.yaml', device='cpu', verbose=False)[0]
                # Pilot stores only detections with an assigned track ID, so match it.
                boxes = result.boxes.xyxy.cpu().tolist() if result.boxes.id is not None else []
                ids = result.boxes.id.int().cpu().tolist() if result.boxes.id is not None else []
                classes = result.boxes.cls.int().cpu().tolist() if result.boxes.id is not None else []
                confidences = result.boxes.conf.cpu().tolist() if result.boxes.id is not None else []
                rows.append({'frame': frame_id, 'detections': [
                    {'id': tid, 'class': cl, 'conf': conf, 'xyxy': box}
                    for tid, cl, conf, box in zip(ids, classes, confidences, boxes)]})
            heat += presence(boxes, w, h, args.grid)
            counts.append(len(boxes))
            # Absolute, fixed scale: 0 is zero frames, 255 is total video frames.
            intensity = np.uint8(np.clip(heat.astype(np.float32) * 255 / total, 0, 255))
            # Repeat cells exactly grid pixels and crop the partial edge cells.
            intensity = np.repeat(np.repeat(intensity, args.grid, axis=0), args.grid, axis=1)[:h, :w]
            present_mask = np.repeat(np.repeat(heat > 0, args.grid, axis=0), args.grid, axis=1)[:h, :w]
            colour = cv2.applyColorMap(intensity, cv2.COLORMAP_TURBO)
            # Alpha is based on the unquantized count: a single detected frame
            # must remain visible even if 8-bit colour rounds its value to zero.
            alpha = np.where(present_mask, 0.58, 0.0).astype(np.float32)[..., None]
            view = np.uint8(frame * (1 - alpha) + colour * alpha)
            for x1,y1,x2,y2 in boxes:
                cv2.rectangle(view, (int(x1),int(y1)), (int(x2),int(y2)), (210,225,240), 1)
            out.write(view)
            if frame_id in (0, total//2, total-1):
                cv2.imwrite(str(Path(args.out).with_name(f'heatmap_frame_{frame_id:03d}.png')), view)
    finally:
        out.release(); cap.release()
    np.save(Path(args.out).with_name('final_counts.npy'), heat)
    result = {'source_sha256': sha256(args.video), 'frames': total, 'fps': fps,
              'size': [w,h], 'cell_px': args.grid, 'grid_shape': list(heat.shape),
              'scale_min_frames': 0, 'scale_max_frames': total,
              'maximum_cell_frames': int(heat.max()), 'nonzero_cells': int(np.count_nonzero(heat)),
              'detections_total': int(sum(counts)), 'frames_with_detections': sum(c > 0 for c in counts),
              'definition': 'number of frames whose cell center lies inside one or more tracked detection boxes'}
    Path(args.out).with_name('heatmap_result.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
    if args.save_cache:
        key = {'source_sha256': sha256(args.video), 'weights_sha256': sha256(args.model),
               'conf': args.confidence, 'classes':[2,3,5,7], 'imgsz':640, 'tracker':'bytetrack.yaml'}
        Path(args.save_cache).write_text(json.dumps({'key':key,'rows':rows}), encoding='utf-8')
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    main()

In this particular run, 263 of the 576 cells received at least one observation; the largest cell total was 201 of 241 frames. These describe the algorithm's detected boxes in this synthetic clip, not confirmed vehicle counts.

How to read the result responsibly

  • Detections are estimates. Missed objects leave gaps and false positives can add heat where there was no vehicle.
  • Box coverage is approximate. A rectangular box is not a segmentation mask, and testing only cell centres misses coverage that does not contain a centre.
  • Time and sampling matter. Results change with the number of sampled frames, frame rate, clip length and how long a vehicle stays in a place. Do not compare raw totals from clips of different lengths without a defined normalization.
  • Perspective matters. Equal-sized image cells do not necessarily represent equal areas on the road. A spatial calibration would be needed for meaningful real-world area or distance measurements.
  • Tracker identities are not verified car counts. An ID can change or disappear. This grid deliberately records box presence per frame; it does not use unique IDs as a count.

For comparison, a line counter answers a different question: how often an observed track crosses a chosen line. See my related traffic-counter article and video walkthrough.

Frequently asked questions

Can this count unique cars?

No. A cell stores detected presence across frames. Counting unique physical cars needs a separate tracking and validation method, and ID changes can still cause errors.

Why can a parked vehicle create a higher-value region?

Because its detected box can cover the same cell centre in many successive frames. The map reflects accumulated observations, not automatically traffic volume.

Does a blank cell prove no vehicle was there?

No. The model may miss a vehicle, a bounding box may cover only part of the cell without covering its centre, or the vehicle may be outside the frame.

For more on the underlying tools, see the official Ultralytics tracking documentation and OpenCV colour maps. Ultralytics also documents a separate heatmap solution; its implementation is distinct from the grid rule explained here.

If you would like to study more Python, OpenCV and YOLO projects, explore my Computer Vision course on Udemy. This is my instructor referral link.

Saturday, November 21, 2026

Sobel vs Canny Edge Detection in Python: An OpenCV Tutorial

How does a computer turn a photograph into lines? In this hands-on Python example, we compare two ways of finding intensity changes: Sobel derivatives and Canny edge detection. You will see the same input image, a gradient-strength map, and a binary edge map.

Watch the visual explanation: Sobel vs Canny Short. For the complete walkthrough, watch the Python and OpenCV tutorial.

What is an edge?

An edge is a location where pixel intensity changes sharply. A dark object against a bright background can create an edge, but so can a shadow, texture, or noise. An edge detector identifies changes in the image; it does not identify an object or understand its meaning.

How Sobel responds to changes

Sobel uses small, fixed kernels to approximate intensity derivatives. One derivative measures change along the x direction and another along y. Combining their values provides a gradient-strength map: brighter pixels in our visualization indicate a stronger response after the gradient magnitude is clipped to the 0–255 display range.

A filter scanning across an image is a useful way to understand the computation. The Sobel kernel is chosen by us; it is not a trained neural-network filter. If you want the background on sliding kernels, see How CNN Filters Find Edges.

What Canny adds

Canny is a multi-stage edge detector. Its stages include gradient estimation, thinning candidate edges through non-maximum suppression, and hysteresis thresholding. In this example, we apply Gaussian blur before Canny to reduce sensitivity to noise. The Sobel result uses unblurred grayscale, matching the course exercise. This makes the demonstration useful for exploring each step, but it is not a comparison with identical preprocessing.

The two Canny thresholds work together: strong candidate edges are kept; weaker candidates can be kept when connected to a strong edge. Changing thresholds can remove noise or detail, but the best settings depend on the input image. cv2.Canny does not automatically perform the separate Gaussian blur shown in this example.

Try it with Python and OpenCV

Install Python, then install the dependencies in your environment:

python -m pip install opencv-python numpy

To recreate the geometric image used in the video, save the following code as generate_input.py and run python generate_input.py in a new folder. It creates input.png; it stops if that file already exists so it does not overwrite your image.

"""Generate the seeded synthetic geometric image used in course lesson 07.

Run: python generate_input.py
Requires: pip install opencv-python numpy
"""
from pathlib import Path
import cv2
import numpy as np

rng = np.random.default_rng(7)
img = np.zeros((480, 640, 3), dtype=np.uint8)
img[:] = (30, 25, 45)
cv2.rectangle(img, (80, 80), (280, 280), (200, 180, 100), -1)
cv2.circle(img, (450, 180), 110, (100, 200, 180), -1)
cv2.ellipse(img, (320, 380), (120, 60), 30, 0, 360, (180, 100, 200), -1)
cv2.line(img, (60, 400), (580, 440), (220, 220, 80), 4)
noise = rng.normal(0, 8, img.shape).astype(np.int16)
img = np.clip(img.astype(np.int16) + noise, 0, 255).astype(np.uint8)
output = Path(__file__).resolve().parent / 'input.png'
if output.exists():
    raise SystemExit(f'File already exists: {output}. Choose a clean folder to avoid overwriting it.')
if not cv2.imwrite(str(output), img):
    raise RuntimeError(f'Unable to write {output}')
print(f'Saved {output}')

Now save the following script as sobel_canny.py in the same folder and run python sobel_canny.py. To use your own image instead, run python sobel_canny.py YOUR_IMAGE.jpg, replacing the name with the actual filename or path. Use an image you have the right to use.

"""Sobel gradient magnitude and Canny edges, based on course lesson 07.

Run: python sobel_canny.py [input_image]
Requires: pip install numpy opencv-python
Outputs are written alongside the script. Canny operates on blurred grayscale;
Sobel operates on unblurred grayscale, matching the lesson notebook.
"""
from pathlib import Path
import json
import sys

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
source = Path(sys.argv[1]) if len(sys.argv) > 1 else HERE / "input.png"
image = cv2.imread(str(source), cv2.IMREAD_COLOR)
if image is None:
    raise SystemExit(f"Cannot read image: {source}")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
gx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
gy = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
magnitude = np.sqrt(gx**2 + gy**2)
sobel = np.uint8(np.clip(magnitude, 0, 255))

def save(name, pixels):
    path = HERE / name
    if not cv2.imwrite(str(path), pixels):
        raise RuntimeError(f"Failed to write {path}")

save("sobel_magnitude.png", sobel)
measurements = {}
for low, high in [(20, 60), (50, 150), (100, 200), (150, 250)]:
    edges = cv2.Canny(blurred, low, high)
    assert edges.shape == gray.shape and set(np.unique(edges)).issubset({0, 255})
    save(f"canny_{low}_{high}.png", edges)
    measurements[f"{low}/{high}"] = int(np.count_nonzero(edges))
results = {
    "input": str(source.name), "width": int(image.shape[1]), "height": int(image.shape[0]),
    "opencv": cv2.__version__, "numpy": np.__version__,
    "canny_nonzero_pixels": measurements,
    "sobel_nonzero_pixels": int(np.count_nonzero(sobel)),
    "interpretation": "Canny is binary; Sobel shows clipped gradient magnitude. Counts are not accuracy measurements."
}
(HERE / "measurements.json").write_text(json.dumps(results, indent=2), encoding="utf-8")
print(json.dumps(results, indent=2))

The script saves sobel_magnitude.png, four Canny images for threshold pairs 20/60, 50/150, 100/200 and 150/250, and measurements.json in the script folder. Those counts report nonzero pixels; they are not accuracy scores or object counts. The demonstration was tested with OpenCV 4.13.0 and NumPy 2.3.5. Versions and image input can affect results. Re-running the processing script overwrites its output files.

Compare the results

  • Sobel: the displayed map shows the strength of intensity changes; it is not inherently a binary outline.
  • Canny: the output marks selected edge pixels after thinning and thresholding.
  • Try this: change both Canny thresholds and compare the resulting outlines. Also try a more textured image or change the blur. Do not assume that fewer lines always mean a more accurate result.

Frequently asked questions

Is Canny a neural network?
No. It is a classical, multi-stage image-processing algorithm. It does not learn weights from a training dataset.

Which is better, Sobel or Canny?
It depends on the task. Sobel provides derivatives or gradient strength; Canny is often useful when you want a thinner, binary edge map. Both are sensitive to image content and parameter choices.

Can edges be used to count objects?
They may help with later processing, but edges alone do not reliably count objects. Broken boundaries, touching objects, lighting and texture can lead to mistakes.

Continue learning

Explore the computer vision course overview and my English-language course, Computer Vision: OpenCV, Machine Learning and YOLO. The course includes hands-on lessons on image operations, edge detection and further computer vision techniques. This is my instructor referral link.

Further reading: OpenCV: Sobel derivatives and OpenCV: Canny edge detection.

Why Does SQL Skip Rank 3? ROW_NUMBER vs RANK vs DENSE_RANK

Watch the tutorial

Watch the full SQL ranking tutorial or the short introduction.

Two people share second place. Does the next person finish third or fourth? In SQL, the answer depends on the ranking function you choose. That choice can change a leaderboard or a top courses report even when the input data is the same.

We will run a small PostgreSQL example, look at the rows, and then rank courses within each category. The data below is synthetic: it does not change any database tables. You can run each complete SQL block in pgAdmin's Query Tool or another PostgreSQL client.

Four scores, one tie

IDParticipantScore
1Anna100
2Ben90
3Chris90
4Dana80

Ben and Chris have the same score. This self-contained query shows all three rankings side by side:

WITH scores (id, participant, score) AS (
    VALUES (1, 'Anna', 100), (2, 'Ben', 90),
           (3, 'Chris', 90), (4, 'Dana', 80)
)
SELECT participant, score,
       ROW_NUMBER() OVER (ORDER BY score DESC, id) AS row_num,
       RANK()       OVER (ORDER BY score DESC) AS rank_num,
       DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank_num
FROM scores
ORDER BY score DESC, id;

WITH ... VALUES supplies a temporary set of input rows for this query; it does not create a table. The OVER clause determines how each window function orders its input. The final ORDER BY controls the order in which the query displays the result.

participantscorerow_numrank_numdense_rank_num
Anna100111
Ben90222
Chris90322
Dana80443

ROW_NUMBER: one sequence number per row

ROW_NUMBER() assigns a different position to each row. Both 90-point rows still represent a tie by score, but their row numbers must differ. Here, id is a unique tie-breaker: Ben has a smaller ID, so he receives 2. If we ordered by score alone, PostgreSQL would not promise which tied row gets which number. This is useful when the requirement is to select a fixed number of rows and a deterministic tie-breaker is acceptable.

RANK: equal scores share a rank; gaps remain

RANK() assigns 2 to both 90-point rows. Since two rows have already occupied positions 2 and 3, the next rank is 4. Choose it when equal values should share a rank and the gap reflects the number of preceding rows.

DENSE_RANK: equal scores share a rank; no gaps

DENSE_RANK() also assigns 2 to both 90-point rows, but the next distinct score receives 3. Choose it when you want consecutive ranks for distinct score levels.

The distinction comes from what counts as a peer. The ordering inside RANK() and DENSE_RANK() uses score alone, so the two 90s are peers. Adding a unique id to those two window orderings would make them different peers and eliminate the intended tie. We use id in the ROW_NUMBER() ordering, and separately in the final display ordering; that final sort does not change the ranks. PostgreSQL documents these functions in Window Functions.

Rank courses separately in each category

Suppose a training company wants the two highest ranks in each category, including every course tied at second place. The next example supplies seven fictional courses; the values are an illustration, not counts from a live TrainingHub database.

WITH courses (course_id, category, course_name, enrollments) AS (
    VALUES (1, 'Java', 'Java Basics', 80),
           (2, 'Java', 'Spring Intro', 70),
           (3, 'Java', 'Java Testing', 70),
           (4, 'SQL', 'SQL Basics', 100),
           (5, 'SQL', 'SQL Joins', 90),
           (6, 'SQL', 'SQL Reports', 90),
           (7, 'SQL', 'SQL Views', 80)
), ranked AS (
    SELECT course_id, category, course_name, enrollments,
           ROW_NUMBER() OVER (
               PARTITION BY category ORDER BY enrollments DESC, course_id
           ) AS row_num,
           RANK() OVER (
               PARTITION BY category ORDER BY enrollments DESC
           ) AS course_rank
    FROM courses
)
SELECT category, course_name, enrollments, row_num, course_rank
FROM ranked
WHERE course_rank <= 2
ORDER BY category, enrollments DESC, course_id;

PARTITION BY category starts a separate ranking for Java and SQL. The inner CTE calculates ranks for each course; the outer query filters them. The SQL result is:

categorycourse_nameenrollmentsrow_numcourse_rank
JavaJava Basics8011
JavaSpring Intro7022
JavaJava Testing7032
SQLSQL Basics10011
SQLSQL Joins9022
SQLSQL Reports9032

Each category returns three courses, not two: both courses tied for second place satisfy course_rank <= 2. If the requirement is at most two rows per category, use WHERE row_num <= 2 instead. For this fixture that selects Java Basics, Spring Intro, SQL Basics and SQL Joins. It intentionally excludes one tied course in each category using course_id as the tie-breaker. If a category has fewer than two courses, it returns only the rows available.

DENSE_RANK() <= 2 would select the first two distinct enrollment-count levels per category. It can return more than two rows as well. More generally, RANK() <= N and DENSE_RANK() <= N need not return the same set because RANK can have gaps. Write the business rule first: exactly N rows where available, ranks with gaps, or N distinct value levels.

Common mistakes to avoid

  • Confusing display order with rank order. The final ORDER BY sorts the output. The ORDER BY inside each OVER defines that function's ranking.
  • Accidentally removing ties. A unique identifier inside RANK or DENSE_RANK makes rows with equal scores non-peers. Use an ID only where it is part of the intended ranking rule.
  • Assuming ROW_NUMBER() is reproducible with ties. Provide an explicit, unique tie-breaker if a stable choice matters.
  • Filtering a window value in the same query's WHERE. Calculate it in a CTE or subquery, then filter in the outer query. See the PostgreSQL window-function tutorial.
  • Ignoring missing values. These examples use non-null scores. If real data can contain NULL, decide where those rows belong and specify an appropriate NULLS FIRST or NULLS LAST rule. Do not treat a missing score as zero without a reason.

Try it yourself

Change Dana's score to 90. Predict all three columns before running the first query again. Which function gives three rows the same rank? Which one continues without a gap? For another exercise, change the second query to return at most two rows per category and verify which tied course is excluded.

For more practice with PostgreSQL, SQL and a synthetic training-business database, explore Practical SQL with PostgreSQL: From Queries to Real Projects. This is the instructor's referral link. The example above runs independently of the paid course.

Friday, November 20, 2026

How CNN Filters Find Edges: A 3×3 Convolution Example in Python

How can a convolutional neural network (CNN) begin to find useful patterns in an image? One building block is a small filter that moves across pixel values. At each position, it combines a local patch of pixels with the filter's weights to produce one number.

In this tutorial, we follow a 3×3 edge filter across a tiny image, calculate a value by hand, and reproduce the complete result in Python. The example uses a hand-picked filter to explain an operation used in CNNs; it is not an activation taken from a trained network.

Watch the moving filter and feature map in the YouTube Short.

1. The image and the filter

Our grayscale image is a 5×5 grid. Each row is identical. Here, 0 represents black and 255 represents white:

  0  255  255  255    0
  0  255  255  255    0
  0  255  255  255    0
  0  255  255  255    0
  0  255  255  255    0

The example filter has three identical rows. It subtracts the left side of each patch from the right side:

-1   0   1
-1   0   1
-1   0   1

This filter is sensitive to changes from left to right, so it responds to vertical boundaries. Different filters respond to different patterns.

2. Calculate the first output value

Place the filter over the upper-left 3×3 patch. Multiply each pixel by the weight at the same position and sum all nine products. Because the three rows in this particular patch are identical, we can show the calculation for one row and multiply its result by three:

One row: 0 × -1 + 255 × 0 + 255 × 1 = 255
Three rows: 255 + 255 + 255 = 765

The first output cell is therefore +765. Move the filter one pixel to the right and repeat. In the middle patch, all pixel values are 255, so the positive and negative contributions cancel and the output is 0. At the right boundary the response is -765.

3. From a moving filter to a feature map

We move one pixel at a time (stride 1) and do not add a border (no padding). The filter fits in three positions across and three down, so the 5×5 input produces a 3×3 output: (5 − 3 + 1) × (5 − 3 + 1).

 765   0  -765
 765   0  -765
 765   0  -765

These are signed raw responses. In this example, +765 and -765 indicate opposite directions of the same kind of brightness change. Zero appears for the uniform middle patch; it does not prove that every possible image patch with a zero response is uniform. Taking an absolute value, clipping values, or applying an activation changes how the output is interpreted.

4. Run the calculation in Python

You need Python and NumPy. If NumPy is not installed in your chosen environment, run python -m pip install numpy. Save the code below as cnn_filter_example.py and run python cnn_filter_example.py. No image file, model weights, or GPU is required.

import numpy as np

# Five identical rows make a simple grayscale image.
# Signed integers preserve negative results.
image = np.array([[0, 255, 255, 255, 0]] * 5, dtype=np.int32)
kernel = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=np.int32)

# Valid cross-correlation: stride 1, no padding, no flipped kernel.
feature_map = np.zeros((3, 3), dtype=np.int32)
for row in range(feature_map.shape[0]):
    for col in range(feature_map.shape[1]):
        patch = image[row:row + 3, col:col + 3]
        feature_map[row, col] = np.sum(patch * kernel)

print('First patch:')
print(image[:3, :3])
print('First output value:', feature_map[0, 0])
print('Signed feature map:')
print(feature_map)
np.testing.assert_array_equal(feature_map, [[765, 0, -765]] * 3)

The assertion checks this particular fixture; it is not a test of a trained model's accuracy. Using a signed integer type matters: unsigned pixel types cannot represent -765 directly.

How does this relate to a CNN?

A convolutional layer applies filters to local patches to create feature maps. A real CNN can use multiple filters, input channels, biases, nonlinear activations and other layers. Its filter weights are usually learned during training. Here we chose the numbers ourselves to make the calculation easy to inspect; we did not train or run a CNN.

Strictly speaking, this example does cross-correlation: it does not flip the kernel before applying it. CNN libraries commonly call this operation convolution. The PyTorch Conv2d documentation describes the cross-correlation operation used by that layer.

Try it yourself

Reverse each filter row to [1, 0, -1] and run the script again after removing or updating the assertion. Can you predict the new signs? Keep the image and all other code unchanged. The positive and negative outputs should exchange signs, while the middle column remains zero.

Frequently asked questions

Why is the output smaller than the input?
With a 3×3 filter, stride 1 and no padding, the filter can start at only three rows and three columns of a 5×5 input. Padding and stride change the output dimensions.

Are CNN filters always edge detectors?
No. Filters are learned for the task; the patterns and their interpretation depend on the trained network, layer and input.

Does a negative value mean an error?
No. A negative value is a valid signed response. Here its sign reflects the direction of the brightness change relative to our chosen filter.

Continue learning

Watch the short animation to follow the moving window. Read the course overview on this blog. My English-language course Computer Vision: OpenCV, Machine Learning and YOLO includes a hands-on lesson on convolution. This is my instructor referral link.