|
1 | | -import numpy as np |
| 1 | +import argparse |
| 2 | +import json |
2 | 3 | import cv2 |
3 | | -import sys |
4 | 4 |
|
5 | | -img = cv2.imread(sys.argv[1], 0) |
6 | | -cv2.imwrite(sys.argv[2], img) |
| 5 | +def main(): |
| 6 | + # Create argument parser |
| 7 | + parser = argparse.ArgumentParser(description='Process an image and optionally write info JSON.') |
| 8 | + parser.add_argument('--in', dest='input_file', required=True, help='Input image file path') |
| 9 | + parser.add_argument('--out', dest='output_file', required=True, help='Output image file path') |
| 10 | + parser.add_argument('--info', dest='info', help='JSON string with additional information') |
| 11 | + |
| 12 | + # Parse arguments |
| 13 | + args = parser.parse_args() |
| 14 | + |
| 15 | + # Read the image in grayscale |
| 16 | + img = cv2.imread(args.input_file, cv2.IMREAD_GRAYSCALE) |
| 17 | + if img is None: |
| 18 | + raise ValueError(f"Cannot read image from {args.input_file}") |
| 19 | + |
| 20 | + data = None |
| 21 | + if args.info: |
| 22 | + try: |
| 23 | + data = json.loads(args.info) |
| 24 | + except json.JSONDecodeError: |
| 25 | + raise ValueError("The provided --info argument is not valid JSON.") |
| 26 | + |
| 27 | + # If external_url exists, render it on the bottom of the image |
| 28 | + external_url = data.get('external_url') |
| 29 | + if external_url: |
| 30 | + # Determine font properties |
| 31 | + font = cv2.FONT_HERSHEY_SIMPLEX |
| 32 | + font_scale = 1.0 |
| 33 | + font_thickness = 2 |
| 34 | + text_color = (128, 128, 128) # grey in BGR |
| 35 | + bg_color = (0, 0, 0) # black |
| 36 | + text = external_url |
| 37 | + |
| 38 | + # Get text size |
| 39 | + (text_width, text_height), _ = cv2.getTextSize(text, font, font_scale, font_thickness) |
| 40 | + |
| 41 | + # Calculate positions |
| 42 | + img_height, img_width = img.shape |
| 43 | + x = (img_width - text_width) // 2 # center horizontally |
| 44 | + y = img_height - 10 # some padding from the bottom |
| 45 | + |
| 46 | + # Determine where to draw background rectangle |
| 47 | + # We'll place a black rectangle that comfortably fits the text |
| 48 | + rect_top_left = (0, img_height - text_height - 20) |
| 49 | + rect_bottom_right = (img_width, img_height) |
| 50 | + cv2.rectangle(img, rect_top_left, rect_bottom_right, bg_color, -1) |
| 51 | + |
| 52 | + # Now put the text on top of the rectangle |
| 53 | + cv2.putText(img, text, (x, y), font, font_scale, text_color, font_thickness, cv2.LINE_AA) |
| 54 | + |
| 55 | + # Write the processed image |
| 56 | + if not cv2.imwrite(args.output_file, img): |
| 57 | + raise ValueError(f"Cannot write image to {args.output_file}") |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + main() |
0 commit comments