Dataset / data_processing /01_deidentification /test_deidentify_trial.py
Kaphathy's picture
Add standalone data_processing directory with per-script dataset mapping and detailed purpose comments
fe5b36e verified
Raw History Blame Contribute Delete
7.66 kB
"""
================================================================================
脚本名称 (Script Name): test_deidentify_trial.py
原本用途 (Original Purpose):
几何掩模提取与脱敏算法单元回归测试套件。确保不同长宽比、不同黑边占比的眼底图像在裁切脱敏时视网膜有效组织不会被误切。
适用数据集 (Target Dataset):
典型异常尺寸、强眩光、偏心光照的测试集样本。
作者与归属 (Author/Provenance):
李思成 (Lisicheng), 浙江大学多模态眼科团队
输入要求 (Input):
合成与极端边界用例图像
输出结果 (Output):
单元测试断言与通过性报告
依赖环境 (Dependencies):
pytest, opencv-python, numpy
================================================================================
"""
import unittest
from argparse import Namespace
from pathlib import Path
import sys
import tarfile
from tempfile import TemporaryDirectory
import cv2
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
from deidentify_batch import metadata_for_row, process_one
from deidentify_trial import (
blackout_frame,
blackout_top_bar,
crop_top_bar,
deidentify_fundus_circle,
deidentify_fundus_left_outside_circle,
parse_ocr_metadata,
)
class DeidentifyTrialTest(unittest.TestCase):
def test_parse_ocr_metadata_keeps_only_non_identifier_fields(self):
meta = parse_ocr_metadata("张三 61岁 男 OD 2021/05/21 15:15")
self.assertEqual(meta, {"age": 61, "sex": "M", "eye": "OD"})
def test_fundus_circle_mask_blacks_corner_and_keeps_retina(self):
img = np.zeros((160, 160, 3), dtype=np.uint8)
yy, xx = np.ogrid[:160, :160]
circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
img[circle] = (90, 80, 70)
img[:16, :35] = (255, 255, 255)
out, ok, _ = deidentify_fundus_circle(img, radius_ratio=0.94, open_kernel=9)
self.assertTrue(ok)
self.assertTrue(np.all(out[4, 4] == 0))
self.assertTrue(np.all(out[80, 80] == img[80, 80]))
def test_left_only_circle_mask_keeps_right_outside_circle(self):
img = np.zeros((160, 160, 3), dtype=np.uint8)
yy, xx = np.ogrid[:160, :160]
circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
img[circle] = (90, 80, 70)
img[4, 4] = (255, 255, 255)
img[4, 150] = (123, 45, 67)
out, ok, _ = deidentify_fundus_left_outside_circle(
img, radius_ratio=0.985, left_ratio=0.55, open_kernel=9
)
self.assertTrue(ok)
self.assertTrue(np.all(out[4, 4] == 0))
self.assertTrue(np.all(out[80, 80] == img[80, 80]))
self.assertTrue(np.array_equal(out[4, 150], img[4, 150]))
def test_blackout_top_bar_preserves_shape_and_masks_top_rows(self):
img = np.full((100, 80, 3), 128, dtype=np.uint8)
out = blackout_top_bar(img, ratio=0.12)
self.assertEqual(out.shape, img.shape)
self.assertTrue(np.all(out[:12] == 0))
self.assertTrue(np.all(out[12:] == 128))
def test_blackout_frame_masks_top_bottom_and_right_without_resizing(self):
img = np.full((100, 80, 3), 128, dtype=np.uint8)
out = blackout_frame(img, top=0.08, bottom=0.05, right=0.02)
self.assertEqual(out.shape, img.shape)
self.assertTrue(np.all(out[:8, :] == 0))
self.assertTrue(np.all(out[95:, :] == 0))
self.assertTrue(np.all(out[:, 78:] == 0))
self.assertTrue(np.all(out[8:95, :78] == 128))
def test_crop_top_bar_removes_requested_fraction(self):
img = np.arange(100 * 80 * 3, dtype=np.uint8).reshape(100, 80, 3)
out = crop_top_bar(img, ratio=0.12)
self.assertEqual(out.shape, (88, 80, 3))
self.assertTrue(np.array_equal(out[0], img[12]))
def test_process_one_bscan_writes_opaque_jpeg_and_metadata(self):
with TemporaryDirectory() as tmp:
tmp_path = Path(tmp)
src = tmp_path / "source.bmp"
img = np.full((100, 80, 3), 128, dtype=np.uint8)
ok, encoded = cv2.imencode(".bmp", img)
self.assertTrue(ok)
encoded.tofile(str(src))
args = Namespace(
out_root=tmp_path / "out",
bscan_top=0.10,
bscan_bottom=0.05,
bscan_right=0.02,
overwrite_images=False,
jpeg_quality=95,
)
row = {
"image_id": "xiangya_bscan_00000001",
"cohort": "xiangya_bscan",
"file_path": str(src),
}
result = process_one(row, args, reader=None)
out_path = tmp_path / "out" / "images" / "xiangya_bscan" / "xiangya_bscan_00000001.jpg"
self.assertTrue(out_path.exists())
self.assertEqual(result["deid_path"], str(out_path))
self.assertEqual(result["deid_method"], "bscan_blackout_top10_bottom5_right2")
self.assertTrue(result["pii_masked"])
def test_process_one_left_fundus_reads_tar_member(self):
with TemporaryDirectory() as tmp:
tmp_path = Path(tmp)
img = np.zeros((160, 160, 3), dtype=np.uint8)
yy, xx = np.ogrid[:160, :160]
circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
img[circle] = (90, 80, 70)
img[4, 4] = (255, 255, 255)
ok, encoded = cv2.imencode(".png", img)
self.assertTrue(ok)
tar_path = tmp_path / "sample.tar"
png_path = tmp_path / "sample.png"
encoded.tofile(str(png_path))
with tarfile.open(tar_path, "w") as tf:
tf.add(png_path, arcname="sample.png")
args = Namespace(
out_root=tmp_path / "out",
overwrite_images=False,
jpeg_quality=95,
fundus_threshold=25,
fundus_open_kernel=9,
left_fundus_radius_ratio=0.985,
left_fundus_ratio=0.55,
)
row = {
"image_id": "tongren_fundus_00000001",
"cohort": "tongren_fundus",
"train_path": f"{tar_path}::sample.png",
"file_path": f"{tar_path}::sample.png",
"ocr_age": 61,
"ocr_sex": "F",
"ocr_eye": "OD",
}
result = process_one(row, args, reader=None)
self.assertTrue(Path(result["deid_path"]).exists())
self.assertEqual(result["deid_method"], "fundus_left_outside_circle_mask_r0985_l055")
self.assertEqual(result["ocr_age"], 61)
self.assertEqual(result["ocr_sex"], "F")
def test_tongren_metadata_is_not_applied_to_fq_rows(self):
meta = {"1005653-1.png": {"age": 63, "sex": "F", "eye": "OD"}}
self.assertEqual(
metadata_for_row(
{
"cohort": "fq_rawfundus",
"rel_path": "1005653-1.png",
"train_path": "/nfs01/FQ_Datasets/data/rawFundus/1005653-1.png",
},
meta,
),
{},
)
self.assertEqual(
metadata_for_row(
{
"cohort": "tongren_fundus",
"rel_path": "1005653-1.png",
"train_path": "/data/team/lisicheng/Dataser/shards_tongren/fundus/a.tar::1005653-1.png",
},
meta,
),
{"age": 63, "sex": "F", "eye": "OD"},
)
if __name__ == "__main__":
unittest.main()