|
4 | 4 | import cv2 as cv |
5 | 5 | import numpy as np |
6 | 6 | import os |
| 7 | +import sys |
7 | 8 |
|
8 | 9 | parser = argparse.ArgumentParser(description= |
9 | 10 | """ |
10 | | -Compares to images by pixels, outputing two different images for the differences. |
| 11 | +Compares candidate images against goldens by pixels, writing one status line |
| 12 | +per image and (optionally) two diff images per image. |
11 | 13 |
|
12 | | -output file {status} |
13 | | -output file {name}.diff0.png |
14 | | - The exact abs(A - B) of each pixel |
15 | | -output file {name}.diff1.png |
16 | | - A mask which has 1 for difference and 0 for no difference at a given pixel |
| 14 | +A single process diffs multiple images in order to amortize the cost of spawning |
| 15 | +the Python interpreter and importing OpenCV (cv2). |
| 16 | +
|
| 17 | +Two ways to feed images to a process: |
| 18 | + --names diff a fixed list of file names, then exit. |
| 19 | + --serve stay alive reading one file name per line from stdin, writing |
| 20 | + "done" to stdout after each, so the parent (diff.py) can pull work |
| 21 | + dynamically and keep every worker busy until the queue is empty. |
| 22 | +
|
| 23 | +output file {status} one status line per image |
| 24 | +output file {name}.diff0.png the exact abs(A - B) of each pixel |
| 25 | +output file {name}.diff1.png a mask which has 255 for difference, 0 otherwise |
17 | 26 | """) |
18 | 27 |
|
19 | | -parser.add_argument("-n", "--name", type=str, required=True, help="name used for output images") |
20 | | -parser.add_argument("-c", "--candidate", type=str, required=True, help="candidate for image diffing") |
21 | | -parser.add_argument("-g", "--golden", type=str, required=True, help="golden to compare against") |
| 28 | +mode = parser.add_mutually_exclusive_group(required=True) |
| 29 | +mode.add_argument("-N", "--names", type=str, nargs='+', help="space-separated image file names (e.g. foo.png bar.png) to diff; each is looked up by name in the --candidate and --golden directories") |
| 30 | +mode.add_argument("--serve", action='store_true', help="read image file names from stdin, one per line, diffing each and writing 'done' to stdout after each; exit on EOF") |
| 31 | +parser.add_argument("-c", "--candidate", type=str, required=True, help="candidate DIRECTORY of images to diff") |
| 32 | +parser.add_argument("-g", "--golden", type=str, required=True, help="golden DIRECTORY to compare against") |
22 | 33 | parser.add_argument("-s", "--status", type=str, required=True, help="output stats file name and location") |
23 | 34 | parser.add_argument("-o", "--outdir", type=str, help="output directory to store image diffs, if not provided then no output image is saved") |
24 | 35 | parser.add_argument("-v", "--verbose", action='store_true', help="enable verbose logging") |
25 | | -parser.add_argument("-l", "--log", action='store_true', help="redirect all verbose logging to a file with --name") |
| 36 | +parser.add_argument("-l", "--log", action='store_true', help="redirect all verbose logging to a per-image file") |
26 | 37 | parser.add_argument("-H", "--histogram", action='store_true', help="compare images using histograms as an additional method for ruling out 'same' images. This should prevent subtle differences in the image that should not be visible from preventing a passing result") |
27 | 38 |
|
28 | 39 | args = parser.parse_args() |
29 | 40 |
|
30 | | -def verbose_log(val): |
| 41 | +def remove_suffix(name, oldsuffix): |
| 42 | + if name.endswith(oldsuffix): |
| 43 | + name = name[:-len(oldsuffix)] |
| 44 | + return name |
| 45 | + |
| 46 | +def verbose_log(name, val): |
31 | 47 | if not args.verbose: |
32 | 48 | return |
33 | 49 | if args.log: |
34 | | - with open(f"tmp/{args.name}.log", "a") as log_file: |
| 50 | + with open(f"tmp/{name}.log", "a") as log_file: |
35 | 51 | log_file.write(val+"\n") |
36 | 52 | else: |
37 | | - print(val) |
38 | | - |
39 | | -def main(): |
40 | | - if args.log: |
41 | | - os.makedirs("tmp", exist_ok=True) |
42 | | - |
| 53 | + print(val, file=sys.stderr) |
| 54 | + |
| 55 | +def diff_one(filename, status): |
| 56 | + name = remove_suffix(filename, ".png") |
| 57 | + candidate_path = os.path.join(args.candidate, filename) |
| 58 | + golden_path = os.path.join(args.golden, filename) |
| 59 | + |
| 60 | + candidate = None |
| 61 | + golden = None |
| 62 | + diff = None |
| 63 | + rgb_diff = None |
| 64 | + mask = None |
| 65 | + total_diff_count = 0 |
| 66 | + max_diff = 0 |
| 67 | + avg = 0.0 |
| 68 | + hist_result = 1.0 |
43 | 69 | size_match = False |
44 | 70 | failed = False |
45 | 71 | try: |
46 | | - verbose_log(f"loading {args.candidate}") |
47 | | - candidate = cv.imread(args.candidate) |
48 | | - verbose_log(f"loading {args.golden}") |
49 | | - golden = cv.imread(args.golden) |
| 72 | + verbose_log(name, f"loading {candidate_path}") |
| 73 | + candidate = cv.imread(candidate_path) |
| 74 | + verbose_log(name, f"loading {golden_path}") |
| 75 | + golden = cv.imread(golden_path) |
50 | 76 |
|
51 | 77 | if candidate is not None and golden is not None: |
52 | 78 | size_match = candidate.shape == golden.shape |
@@ -85,67 +111,99 @@ def main(): |
85 | 111 | hist_candidate = cv.calcHist(hsv_candidate, [0,1], None, histSize, ranges, accumulate=False) |
86 | 112 | hist_golden = cv.calcHist(hsv_golden, [0,1], None, histSize, ranges, accumulate=False) |
87 | 113 |
|
88 | | - # compare using CORREL histogram algorithm. the different options are detailed here |
| 114 | + # compare using CORREL histogram algorithm. the different options are detailed here |
89 | 115 | # https://docs.opencv.org/3.4/d6/dc7/group__imgproc__hist.html#ga994f53817d621e2e4228fc646342d386 |
90 | 116 | # a hist_result of 1.0 means identical with this method. any variance results in a number less then 1.0 |
91 | 117 | hist_result = cv.compareHist(hist_candidate, hist_golden, cv.HISTCMP_CORREL) |
92 | | - |
| 118 | + |
93 | 119 | except Exception as E: |
94 | | - print(f"Failed to load and process images {E}") |
| 120 | + print(f"Failed to load and process images {E}", file=sys.stderr) |
95 | 121 | failed = True |
96 | 122 |
|
| 123 | + status.write(name + "\t") |
| 124 | + if failed: |
| 125 | + status.write("failed\n") |
| 126 | + verbose_log(name, "failed to load golden or candidate") |
| 127 | + return |
| 128 | + if candidate is None: |
| 129 | + status.write("missing_candidate\n") |
| 130 | + verbose_log(name, "missing candidate for " + name) |
| 131 | + return |
| 132 | + if golden is None: |
| 133 | + status.write("missing_golden\n") |
| 134 | + verbose_log(name, "missing golden for " + name) |
| 135 | + return |
| 136 | + if failed: |
| 137 | + status.write("failed\n") |
| 138 | + verbose_log(name, "failed to load golden or candidate") |
| 139 | + return |
| 140 | + if total_diff_count == 0: |
| 141 | + status.write("identical\n") |
| 142 | + verbose_log(name, "files are identical") |
| 143 | + return |
| 144 | + if not size_match: |
| 145 | + status.write("sizemismatch\n") |
| 146 | + verbose_log(name, "files are not the same size") |
| 147 | + return |
| 148 | + status.write(str(max_diff)+"\t") |
| 149 | + # prevent python from writing out in scientific notation |
| 150 | + status.write(f"{float(avg):.5f}\t") |
| 151 | + status.write(str(total_diff_count)+"\t") |
| 152 | + status.write(str(diff.shape[0]*diff.shape[1])) |
| 153 | + # add our histogram result as the last value of the status file or write a new line to say we are finished with this status |
| 154 | + if args.histogram: |
| 155 | + status.write(f"\t{float(hist_result):.5f}\n") |
| 156 | + else: |
| 157 | + status.write("\n") |
| 158 | + |
| 159 | + # save the output files if location provided |
| 160 | + if args.outdir: |
| 161 | + # color diff file location |
| 162 | + c_diff_path = os.path.join(args.outdir, name + ".diff0.png") |
| 163 | + # mask diff file location |
| 164 | + c_mask_path = os.path.join(args.outdir, name + ".diff1.png") |
| 165 | + verbose_log(name, f"writing images {c_diff_path} and {c_mask_path}") |
| 166 | + cv.imwrite(c_diff_path, rgb_diff) |
| 167 | + cv.imwrite(c_mask_path, mask) |
| 168 | + verbose_log(name, "finished writing output images") |
| 169 | + |
| 170 | +def prepare_dirs(): |
| 171 | + if args.log: |
| 172 | + os.makedirs("tmp", exist_ok=True) |
| 173 | + |
97 | 174 | # make path to stats file if necessary |
98 | 175 | if os.path.dirname(args.status): |
99 | | - verbose_log(f"making status file path {os.path.dirname(args.status)}") |
100 | 176 | os.makedirs(os.path.dirname(args.status), exist_ok=True) |
101 | | - verbose_log(f"making status file {args.status}") |
102 | | - with open(args.status, "a") as status: |
103 | | - status.write(args.name + "\t"); |
104 | | - if candidate is None: |
105 | | - status.write("missing_candidate\n") |
106 | | - verbose_log("missing golden for " + args.name) |
107 | | - return |
108 | | - if golden is None: |
109 | | - status.write("missing_golden\n") |
110 | | - verbose_log("missing golden for " + args.name) |
111 | | - return |
112 | | - if failed: |
113 | | - status.write("failed\n") |
114 | | - verbose_log("failed to load golden or candidate") |
115 | | - return |
116 | | - if total_diff_count == 0: |
117 | | - status.write("identical\n") |
118 | | - verbose_log("files are identical") |
119 | | - return |
120 | | - if not size_match: |
121 | | - status.write("sizemismatch\n") |
122 | | - verbose_log("files are not the same size") |
123 | | - return |
124 | | - status.write(str(max_diff)+"\t") |
125 | | - # prevent python from writing out in scientific notation |
126 | | - status.write(f"{float(avg):.5f}\t") |
127 | | - status.write(str(total_diff_count)+"\t") |
128 | | - status.write(str(diff.shape[0]*diff.shape[1])) |
129 | | - # add our histogram result as the last value of the status file or write a new line to say we are finished with this status |
130 | | - if args.histogram: |
131 | | - status.write(f"\t{float(hist_result):.5f}\n") |
132 | | - else: |
133 | | - status.write("\n") |
134 | | - |
135 | | - verbose_log("status file finished") |
136 | | - # save the output file if location provided |
137 | 177 | if args.outdir: |
138 | | - # color diff file location |
139 | | - c_diff_path = os.path.join(args.outdir, args.name + ".diff0.png") |
140 | | - # mask diff file location |
141 | | - c_mask_path = os.path.join(args.outdir, args.name + ".diff1.png") |
142 | | - # create output dir if needed |
143 | | - verbose_log(f"making output directory {args.outdir}") |
144 | 178 | os.makedirs(args.outdir, exist_ok=True) |
145 | | - verbose_log(f"writing images {c_diff_path} and {c_mask_path}") |
146 | | - cv.imwrite(c_diff_path, rgb_diff) |
147 | | - cv.imwrite(c_mask_path, mask) |
148 | | - verbose_log("finished writing output images") |
| 179 | + |
| 180 | +def main(): |
| 181 | + # A single process handles the whole list; open the status file once and |
| 182 | + # append one line per image. |
| 183 | + prepare_dirs() |
| 184 | + with open(args.status, "a") as status: |
| 185 | + for filename in args.names: |
| 186 | + diff_one(filename, status) |
| 187 | + |
| 188 | +def serve(): |
| 189 | + # Interactive worker: the parent (diff.py) keeps this process alive and |
| 190 | + # feeds it one image file name per line on stdin, so cv2 is imported once |
| 191 | + # and then reused across many images. After each image we append its status |
| 192 | + # line to the status file and write "done" to stdout so the parent knows |
| 193 | + # we're ready for the next name. Exit on EOF. |
| 194 | + prepare_dirs() |
| 195 | + with open(args.status, "a") as status: |
| 196 | + for line in sys.stdin: |
| 197 | + filename = line.strip() |
| 198 | + if not filename: |
| 199 | + continue |
| 200 | + diff_one(filename, status) |
| 201 | + status.flush() |
| 202 | + sys.stdout.write("done\n") |
| 203 | + sys.stdout.flush() |
149 | 204 |
|
150 | 205 | if __name__ == '__main__': |
151 | | - main() |
| 206 | + if args.serve: |
| 207 | + serve() |
| 208 | + else: |
| 209 | + main() |
0 commit comments