罗广辉
yesterday 7cc239cee1a9af4e2e8a0f3d5b7a00a074b17214
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import tempfile
import unittest
from pathlib import Path
 
import numpy as np
import rasterio
from rasterio.transform import from_origin
 
import sys
 
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from run_spatial_measurement import process_raster  # noqa: E402
 
 
class SpatialMeasurementTests(unittest.TestCase):
    def test_counts_and_pixel_units(self):
        with tempfile.TemporaryDirectory() as directory:
            root = Path(directory)
            source = root / "normal.tif"
            mask = np.zeros((32, 40), dtype=np.uint8)
            mask[2:8, 3:10] = 1
            mask[18:26, 25:35] = 2
            with rasterio.open(source, "w", driver="GTiff", height=32, width=40, count=1, dtype="uint8", transform=from_origin(0, 0, 1, 1), nodata=0) as dst:
                dst.write(mask, 1)
            result = process_raster(source, root / "out")
            self.assertEqual(result["object_count"], 2)
            self.assertEqual(result["measurement_basis"], "pixel_coordinates")
            self.assertTrue((root / "out" / result["vector_file"]).is_file())
            self.assertTrue((root / "out" / result["csv_file"]).is_file())
 
    def test_difficult_empty_input_fails(self):
        with tempfile.TemporaryDirectory() as directory:
            root = Path(directory)
            source = root / "empty.tif"
            with rasterio.open(source, "w", driver="GTiff", height=8, width=8, count=1, dtype="uint8") as dst:
                dst.write(np.zeros((8, 8), dtype=np.uint8), 1)
            with self.assertRaises(ValueError):
                process_raster(source, root / "out")
 
    def test_projected_crs_uses_map_units(self):
        with tempfile.TemporaryDirectory() as directory:
            root = Path(directory)
            source = root / "projected.tif"
            mask = np.zeros((16, 16), dtype=np.uint8)
            mask[3:9, 4:11] = 1
            with rasterio.open(source, "w", driver="GTiff", height=16, width=16, count=1, dtype="uint8", transform=from_origin(500000, 4000000, 2, 2), crs="EPSG:3857", nodata=0) as dst:
                dst.write(mask, 1)
            result = process_raster(source, root / "out")
            self.assertEqual(result["measurement_basis"], "projected_crs")
            self.assertEqual(result["object_count"], 1)
            self.assertGreater(result["total_area"], 0)
 
 
if __name__ == "__main__":
    unittest.main()