Last active
December 23, 2021 13:00
-
-
Save Bouni/6b54f12174e6e38e2e7c2153d40cb765 to your computer and use it in GitHub Desktop.
Detect map in image to correct its position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| from datetime import datetime as dt | |
| import cv2 | |
| from PIL import Image, ImageDraw, ImageFont | |
| BASEPATH = os.path.abspath(os.path.dirname(__file__)) | |
| # read needle image as grayscale | |
| template = cv2.imread(os.path.join(BASEPATH, "map.png"), 0) | |
| # convert all non white pixels to black | |
| template[template != 255] = 0 | |
| # get the width and height of the map | |
| w, h = template.shape[::-1] | |
| # iterate over all the original images | |
| for image in os.listdir(os.path.join(BASEPATH, "original")): | |
| print(f"Proccess original image {image}") | |
| # parse the date from the filename | |
| date = dt.strptime(image[:10], "%Y-%m-%d").strftime("%d.%m.%Y") | |
| # read the original image in RGB | |
| rgb = cv2.imread(os.path.join(BASEPATH, "original", image)) | |
| # create a gray scale copy of it | |
| gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY) | |
| # convert all non white pixels to black | |
| gray[gray != 255] = 0 | |
| # do a template search of the black and white map on the black and whit original | |
| res = cv2.matchTemplate(gray, template, cv2.TM_CCOEFF_NORMED) | |
| # get the best result from all the results | |
| min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) | |
| # get the bounding box of the map in the original | |
| top_left = max_loc | |
| bottom_right = (top_left[0] + w, top_left[1] + h) | |
| # crop the original to the bounding box | |
| rgb = rgb[top_left[1] : top_left[1] + h, top_left[0] : top_left[0] + w] | |
| # save the croped image | |
| cv2.imwrite(os.path.join(BASEPATH, "cropped", f"cropped-{image}"), rgb) | |
| # load the croped image | |
| cropped_map = Image.open(os.path.join(BASEPATH, "cropped", f"cropped-{image}")) | |
| # load the overlay | |
| overlay = Image.open(os.path.join(BASEPATH, f"overlay.png")) | |
| # paste the overlay over the cropped map | |
| cropped_map.paste(overlay, (0, 0), overlay) | |
| # write the date in the top left corner with a slight offset of (10, 10) | |
| draw = ImageDraw.Draw(cropped_map) | |
| font = ImageFont.truetype(os.path.join(BASEPATH, "ubuntu.ttf"), 30) | |
| draw.text((10, 10), date, (0, 0, 0), font=font) | |
| # Save the final result | |
| cropped_map.save(os.path.join(BASEPATH, "final", f"{image}")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment