"""Offline verification lab for OpenCV Chapter 27: C++ OpenCV advanced image processing."""
import json
import cv2
import numpy as np
def case_threshold_edge_and_watershed_segmentation():
# Two slightly touching dark disks on a bright background
img = np.full((200, 200, 3), (240, 240, 240), dtype=np.uint8)
cv2.circle(img, (68, 100), 34, (35, 35, 35), -1)
cv2.circle(img, (132, 100), 34, (35, 35, 35), -1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh_global = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)
thresh_adapt = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
edges = cv2.Canny(gray, 100, 200)
# Watershed pipeline matching source
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel, iterations=2)
sure_bg = cv2.dilate(opened, kernel, iterations=3)
dist = cv2.distanceTransform(opened, cv2.DIST_L2, 5)
cv2.normalize(dist, dist, 0, 1.0, cv2.NORM_MINMAX)
_, sure_fg = cv2.threshold(dist, 0.5, 1.0, cv2.THRESH_BINARY)
dist_8u = (sure_fg * 255).astype(np.uint8)
contours, _ = cv2.findContours(dist_8u, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
markers = np.zeros(dist.shape, dtype=np.int32)
markers[sure_bg == 0] = 1
for i in range(len(contours)):
cv2.drawContours(markers, contours, i, int(i + 2), -1)
cv2.watershed(img, markers)
boundary_px = int(np.count_nonzero(markers == -1))
left_label = int(markers[100, 68])
right_label = int(markers[100, 132])
bg_label = int(markers[10, 10])
actual = dict(
global_white_gt_0=bool(int(np.count_nonzero(thresh_global)) > 0),
adapt_white_gt_0=bool(int(np.count_nonzero(thresh_adapt)) > 0),
canny_edges_gt_0=bool(int(np.count_nonzero(edges)) > 0),
seed_contour_count=len(contours),
disks_separated=bool(left_label >= 2 and right_label >= 2 and left_label != right_label),
bg_label=bg_label,
watershed_boundary_gt_0=bool(boundary_px > 0),
)
expected = dict(
global_white_gt_0=True,
adapt_white_gt_0=True,
canny_edges_gt_0=True,
seed_contour_count=2,
disks_separated=True,
bg_label=1,
watershed_boundary_gt_0=True,
)
return dict(name="threshold_edge_and_watershed_segmentation", passed=actual == expected, expected=expected, actual=actual)
def case_contours_features_and_drawing():
binary = np.zeros((160, 200), dtype=np.uint8)
cv2.rectangle(binary, (20, 30), (79, 69), 255, -1) # 60x40 filled rectangle
cv2.circle(binary, (145, 95), 25, 255, -1)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
areas = sorted([round(float(cv2.contourArea(c)), 1) for c in contours])
rect_contour = max(contours, key=cv2.contourArea)
rect_area = round(float(cv2.contourArea(rect_contour)), 1)
rect_perim = round(float(cv2.arcLength(rect_contour, True)), 1)
bx, by, bw, bh = cv2.boundingRect(rect_contour)
dst = np.zeros((160, 200, 3), dtype=np.uint8)
cv2.drawContours(dst, contours, -1, (0, 255, 0), 2)
actual = dict(
contour_count=len(contours),
hierarchy_shape=list(hierarchy.shape),
rect_area=rect_area,
rect_perim=rect_perim,
rect_bbox=[bx, by, bw, bh],
circle_area_approx=areas[0],
drawn_green_gt_0=bool(int(np.count_nonzero(dst[:, :, 1])) > 0),
)
expected = dict(
contour_count=2,
hierarchy_shape=[1, 2, 4],
rect_area=2301.0,
rect_perim=196.0,
rect_bbox=[20, 30, 60, 40],
circle_area_approx=1890.0,
drawn_green_gt_0=True,
)
return dict(name="contours_features_and_drawing", passed=actual == expected, expected=expected, actual=actual)
def case_morphology_and_histogram_equalization():
# Morphology open + close on noisy binary mask
binary = np.zeros((120, 120), dtype=np.uint8)
binary[30:90, 30:90] = 255
binary[58:61, 58:61] = 0 # internal hole
binary[8:11, 8:11] = 255 # external noise speck
k5 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, k5)
closed = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, k5)
# Low contrast grayscale histogram equalization
low_c = np.tile(np.linspace(80, 120, 120, dtype=np.uint8), (120, 1))
eq = cv2.equalizeHist(low_c)
actual = dict(
open_cleared_speck=bool(int(opened[9, 9]) == 0),
close_filled_hole=bool(int(closed[59, 59]) == 255),
orig_range=[int(low_c.min()), int(low_c.max())],
eq_range=[int(eq.min()), int(eq.max())],
std_ratio_gt_5=bool(float(eq.std()) / float(low_c.std()) > 5.0),
)
expected = dict(
open_cleared_speck=True,
close_filled_hole=True,
orig_range=[80, 120],
eq_range=[0, 255],
std_ratio_gt_5=True,
)
return dict(name="morphology_and_histogram_equalization", passed=actual == expected, expected=expected, actual=actual)
def case_single_and_multi_template_matching():
scene = np.full((200, 240, 3), (40, 50, 60), dtype=np.uint8)
templ = np.zeros((24, 24, 3), dtype=np.uint8)
cv2.rectangle(templ, (2, 2), (21, 21), (200, 140, 40), 2)
cv2.circle(templ, (12, 12), 6, (40, 220, 240), -1)
cv2.line(templ, (3, 20), (20, 3), (255, 255, 255), 2)
targets = [(30, 40), (130, 50), (80, 130)] # (x, y)
for tx, ty in targets:
scene[ty : ty + 24, tx : tx + 24] = templ
res = cv2.matchTemplate(scene, templ, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(res)
# Multi-template extraction via local peak suppression
ys, xs = np.where(res >= 0.98)
found = []
for x, y in sorted(zip(xs.tolist(), ys.tolist())):
if all(abs(x - fx) > 10 or abs(y - fy) > 10 for fx, fy in found):
found.append((x, y))
actual = dict(
result_shape=list(res.shape),
single_max_val_ge_0999=bool(max_val >= 0.999),
single_loc_in_targets=bool(tuple(max_loc) in targets),
multi_found_sorted=sorted(found),
)
expected = dict(
result_shape=[177, 217],
single_max_val_ge_0999=True,
single_loc_in_targets=True,
multi_found_sorted=[[30, 40], [80, 130], [130, 50]],
)
# Normalize tuple list to list of lists for JSON comparison
actual["multi_found_sorted"] = [list(p) for p in actual["multi_found_sorted"]]
return dict(name="single_and_multi_template_matching", passed=actual == expected, expected=expected, actual=actual)
def main():
cases = [
case_threshold_edge_and_watershed_segmentation(),
case_contours_features_and_drawing(),
case_morphology_and_histogram_equalization(),
case_single_and_multi_template_matching(),
]
print(json.dumps({"cases": cases, "figures": {}}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。
入口文件:projects/opencv-cpp-opencv-advanced-image-processing-lab/explore-cpp-opencv-advanced-image-processing.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-cpp-opencv-advanced-image-processing.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a568.zip
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip