I’m trying to crop white from images generated in vpython. I’ve got the code working but am experiencing some weird behavior I do not understand.
An example is this image, i would like it to be cropped such that all the unnececairy white space is removed.
Unfortunatley the image crop is produced wrong. I wanted to post the result here but since im new I can only post one image. My problem is that a lot of the red arrows and red text are cut off, this should not happen.
I have a hard time understanding why this happens, i’ve tried to change the treshold below 254 but that did not work. I also tried to change the colors of the red arrow but that also did not work.
I would figure this should be extremely simple since my background is just 1 color.
Can anyone please explain me what is going on ?
This is my code:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 30 21:26:56 2022 @author: windhoos """ import cv2 import numpy as np #import sys import os # get the path/directory folder_dir = os.path.dirname(__file__) for images in os.listdir(folder_dir): # check if the image ends with png if (images.endswith(".png")): img = cv2.imread(images) info = np.iinfo(img.dtype) # Get the information of the incoming image type img = img.astype(np.float64) / info.max # normalize the data to 0 - 1 img = 255 * img # Now scale by 255 img = img.astype(np.uint8) ## (1) Convert to gray, and threshold gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) th, threshed = cv2.threshold(gray, 254, 255, cv2.THRESH_BINARY_INV) ## (2) Morph-op to remove noise kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11)) morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel) ## (3) Find the max-area contour cnts = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] cnt = sorted(cnts, key=cv2.contourArea)[-1] ## (4) Crop and save it x,y,w,h = cv2.boundingRect(cnt) dst = img[y:y+h, x:x+w] cv2.imwrite('cv_'+images, dst)
This code is adopted from here.
Thank you very much in advance. Sorry for the probably noob question