"""Independent offline OpenCV image-basic lab: full pipeline from attributes/IO/ROI to edges, morphology, contours & video."""
import json
import platform
import tempfile
from pathlib import Path
import cv2
import numpy as np
def run_cases():
cases = []
# 1. Image attributes, IO, pixel access, ROI, and channel split/merge
img = np.zeros((200, 240, 3), dtype=np.uint8)
img[:, :] = (40, 90, 180)
cv2.rectangle(img, (20, 20), (180, 160), (200, 120, 50), -1)
img_f32 = img.astype(np.float32) / 255.0
with tempfile.TemporaryDirectory() as tmp:
p_ok = Path(tmp) / "output_image.png"
cv2.imwrite(str(p_ok), img)
reloaded = cv2.imread(str(p_ok))
missing = cv2.imread(str(Path(tmp) / "missing.jpg"))
work = reloaded.copy()
orig_px = work[100, 100].tolist()
work[100, 100] = [255, 255, 255]
work[50:150, 50:150] = [0, 255, 0]
b, g, r = cv2.split(work)
merged = cv2.merge([b, g, r])
ok1 = (
reloaded.shape == (200, 240, 3)
and reloaded.dtype == np.uint8
and img_f32.dtype == np.float32
and missing is None
and orig_px == [200, 120, 50]
and work[100, 100].tolist() == [0, 255, 0]
and np.array_equal(work, merged)
)
cases.append(dict(
name="image_attrs_io_pixel_roi_channels",
inputs=dict(shape=[200, 240, 3], roi=[50, 150, 50, 150]),
prerequisites="200x240 合成 BGR uint8 图像及对应 float32 归一化副本",
action="验证 shape/dtype、imread/imwrite 读写与缺失返回 None、像素修改、ROI 赋绿及 split/merge 无损还原。",
expected=dict(
shape=[200, 240, 3],
missing_is_none=True,
orig_pixel=[200, 120, 50],
roi_green=[0, 255, 0],
merge_equal=True,
),
actual=dict(
shape=list(reloaded.shape),
missing_is_none=(missing is None),
orig_pixel=orig_px,
roi_green=work[100, 100].tolist(),
merge_equal=bool(np.array_equal(work, merged)),
),
measurements=dict(
uint8_dtype=str(reloaded.dtype),
float32_max=round(float(img_f32.max()), 4),
channel_shape=list(b.shape),
),
passed=ok1,
))
# 2. Geometry transforms & color space conversions (GRAY, HSV, YUV)
resized = cv2.resize(img, (120, 100))
cropped = img[20:120, 30:150]
h, w = img.shape[:2]
m_rot = cv2.getRotationMatrix2D((w // 2, h // 2), 30, 1.0)
rotated = cv2.warpAffine(img, m_rot, (w, h))
m_trans = np.float32([[1, 0, 25], [0, 1, 15]])
translated = cv2.warpAffine(img, m_trans, (w, h))
flip_v = cv2.flip(img, 0)
flip_h = cv2.flip(img, 1)
flip_both = cv2.flip(img, -1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
ok2 = (
resized.shape == (100, 120, 3)
and cropped.shape == (100, 120, 3)
and rotated.shape == translated.shape == (200, 240, 3)
and np.array_equal(cv2.flip(flip_h, 1), img)
and np.array_equal(cv2.flip(flip_v, 0), img)
and np.array_equal(cv2.flip(flip_both, -1), img)
and gray.shape == (200, 240)
and hsv.shape == (200, 240, 3)
and yuv.shape == (200, 240, 3)
)
cases.append(dict(
name="geometry_and_color_spaces",
inputs=dict(resize_wh=[120, 100], angle=30, shift=[25, 15]),
prerequisites="原始 200x240 BGR 图像",
action="测试 resize、切片裁剪、旋转/平移仿射、三向 flip 可逆性,以及 BGR 到 GRAY/HSV/YUV 颜色空间转换。",
expected=dict(
resized_shape=[100, 120, 3],
cropped_shape=[100, 120, 3],
flips_reversible=True,
gray_shape=[200, 240],
),
actual=dict(
resized_shape=list(resized.shape),
cropped_shape=list(cropped.shape),
flips_reversible=bool(
np.array_equal(cv2.flip(flip_h, 1), img)
and np.array_equal(cv2.flip(flip_v, 0), img)
and np.array_equal(cv2.flip(flip_both, -1), img)
),
gray_shape=list(gray.shape),
),
measurements=dict(
center_gray=int(gray[100, 100]),
center_hsv=hsv[100, 100].tolist(),
center_yuv=yuv[100, 100].tolist(),
),
passed=ok2,
))
# 3. Arithmetic, thresholding, and smoothing overview
a = np.full((60, 60), 200, dtype=np.uint8)
b_arr = np.full((60, 60), 100, dtype=np.uint8)
added = cv2.add(a, b_arr)
subbed = cv2.subtract(b_arr, a)
blended = cv2.addWeighted(a, 0.7, b_arr, 0.3, 0)
bimodal = np.full((100, 100), 50, dtype=np.uint8)
bimodal[20:80, 20:80] = 210
ret_fix, th_fix = cv2.threshold(bimodal, 127, 255, cv2.THRESH_BINARY)
th_adap = cv2.adaptiveThreshold(bimodal, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
ret_otsu, th_otsu = cv2.threshold(bimodal, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
s_mean = cv2.blur(bimodal, (5, 5))
s_gauss = cv2.GaussianBlur(bimodal, (5, 5), 0)
s_med = cv2.medianBlur(bimodal, 5)
s_bi = cv2.bilateralFilter(bimodal, 9, 75, 75)
ok3 = (
int(added[0, 0]) == 255
and int(subbed[0, 0]) == 0
and int(blended[0, 0]) == 170
and int(ret_fix) == 127
and int(ret_otsu) == 50
and np.array_equal(th_fix, th_otsu)
and th_adap.shape == (100, 100)
and s_mean.shape == s_gauss.shape == s_med.shape == s_bi.shape == (100, 100)
)
cases.append(dict(
name="arithmetic_threshold_smoothing",
inputs=dict(a_val=200, b_val=100, weights=[0.7, 0.3, 0]),
prerequisites="固定亮度常量图与双峰 50/210 灰度方块图",
action="验证饱和加减、加权混合、简单/自适应/Otsu 阈值化以及均值/高斯/中值/双边四种滤波。",
expected=dict(add_sat=255, sub_sat=0, blend_val=170, otsu_matches_fixed=True),
actual=dict(
add_sat=int(added[0, 0]),
sub_sat=int(subbed[0, 0]),
blend_val=int(blended[0, 0]),
otsu_matches_fixed=bool(np.array_equal(th_fix, th_otsu)),
),
measurements=dict(
otsu_threshold=float(ret_otsu),
edge_grad_gauss=int(abs(int(s_gauss[20, 50]) - int(s_gauss[19, 50]))),
edge_grad_bilateral=int(abs(int(s_bi[20, 50]) - int(s_bi[19, 50]))),
),
passed=ok3,
))
# 4. Edge detection (Canny/Sobel/Laplacian), morphology (erode/dilate/open/close), and contours
bin_img = np.zeros((120, 160), dtype=np.uint8)
cv2.rectangle(bin_img, (20, 20), (70, 95), 255, -1)
cv2.circle(bin_img, (120, 60), 25, 255, -1)
# Add small noise dot & pinhole to prove opening & closing
bin_with_defects = bin_img.copy()
bin_with_defects[5:8, 5:8] = 255
bin_with_defects[55:58, 42:45] = 0
edges = cv2.Canny(bin_img, 100, 200)
sobel_x = cv2.Sobel(bin_img, cv2.CV_64F, 1, 0, ksize=5)
sobel_y = cv2.Sobel(bin_img, cv2.CV_64F, 0, 1, ksize=5)
lap = cv2.Laplacian(bin_img, cv2.CV_64F)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
eroded = cv2.erode(bin_img, kernel, iterations=1)
dilated = cv2.dilate(bin_img, kernel, iterations=1)
opened = cv2.morphologyEx(bin_with_defects, cv2.MORPH_OPEN, kernel)
closed = cv2.morphologyEx(bin_with_defects, cv2.MORPH_CLOSE, kernel)
contours, _ = cv2.findContours(bin_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
drawn = cv2.cvtColor(bin_img, cv2.COLOR_GRAY2BGR)
cv2.drawContours(drawn, contours, -1, (0, 255, 0), 3)
ok4 = (
int(np.count_nonzero(edges)) > 200
and float(np.max(np.abs(sobel_x))) > 0
and float(np.max(np.abs(sobel_y))) > 0
and float(np.max(np.abs(lap))) > 0
and int(np.count_nonzero(eroded)) < int(np.count_nonzero(bin_img)) < int(np.count_nonzero(dilated))
and int(opened[6, 6]) == 0
and int(closed[56, 43]) == 255
and len(contours) == 2
)
cases.append(dict(
name="edges_morphology_contours",
inputs=dict(shapes=2, kernel=[5, 5]),
prerequisites="含矩形与圆形前景及孤立噪点/小孔洞的 120x160 二值图",
action="验证 Canny/Sobel/Laplacian 边缘、腐蚀收缩/膨胀扩展、开运算去噪/闭运算填孔,以及外部轮廓检测与绘制。",
expected=dict(
erode_lt_orig_lt_dilate=True,
open_removed_speck=True,
close_filled_hole=True,
external_contours=2,
),
actual=dict(
erode_lt_orig_lt_dilate=(
int(np.count_nonzero(eroded)) < int(np.count_nonzero(bin_img)) < int(np.count_nonzero(dilated))
),
open_removed_speck=(int(opened[6, 6]) == 0),
close_filled_hole=(int(closed[56, 43]) == 255),
external_contours=len(contours),
),
measurements=dict(
orig_white=int(np.count_nonzero(bin_img)),
eroded_white=int(np.count_nonzero(eroded)),
dilated_white=int(np.count_nonzero(dilated)),
canny_edges=int(np.count_nonzero(edges)),
),
passed=ok4,
))
# 5. Offline VideoWriter + VideoCapture roundtrip (4 frames MJPG AVI)
with tempfile.TemporaryDirectory() as tmp:
vid_path = str(Path(tmp) / "demo.avi")
writer = cv2.VideoWriter(vid_path, cv2.VideoWriter_fourcc(*"MJPG"), 10.0, (80, 60))
opened_w = writer.isOpened()
for i in range(4):
frame = np.full((60, 80, 3), i * 60, dtype=np.uint8)
writer.write(frame)
writer.release()
cap = cv2.VideoCapture(vid_path)
read_shapes = []
while cap.isOpened():
ret, frm = cap.read()
if not ret:
break
read_shapes.append(list(frm.shape))
cap.release()
ok5 = opened_w and len(read_shapes) == 4 and all(s == [60, 80, 3] for s in read_shapes)
cases.append(dict(
name="video_capture_writer_roundtrip",
inputs=dict(frames=4, size_wh=[80, 60], fourcc="MJPG"),
prerequisites="在临时目录写入 4 帧 MJPG AVI 测试视频后使用 cv2.VideoCapture 逐帧读取",
action="验证 VideoCapture 循环读取全部 4 帧、每帧形状 (60, 80, 3) 及 cap.release() 正常释放。",
expected=dict(writer_opened=True, frames_read=4, frame_shape=[60, 80, 3]),
actual=dict(
writer_opened=bool(opened_w),
frames_read=len(read_shapes),
frame_shape=read_shapes[0] if read_shapes else None,
),
measurements=dict(all_shapes_identical=(len(read_shapes) == 4 and all(s == [60, 80, 3] for s in read_shapes))),
passed=ok5,
))
print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))
if __name__ == "__main__":
run_cases()
本例需在 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-image-basic-lab/explore-image-basic.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-image-basic.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a581.zip