F*CK YEAH found my solution.
Thank you for helping! It helped a lot!
#!/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, 120, 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 contours
contours, hierarchy = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
xmin=[]
xmax=[]
ymin=[]
ymax=[]
for c in contours:
x,y,w,h = cv2.boundingRect(c)
xmin.append(x)
xmax.append(x+w)
ymin.append(y)
ymax.append(y+h)
xmin=min(xmin)
xmax=max(xmax)
ymin=min(ymin)
ymax=max(ymax)
cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0,0,0), 2)
dst = img[ymin:ymax, xmin:xmax]
cv2.imwrite('cv_'+images, dst)