k4d3 commited on
Commit
bf0831b
1 Parent(s): 71e076c

i hope this works

Browse files

Signed-off-by: Balazs Horvath <[email protected]>

Files changed (1) hide show
  1. img_remove_white_border +45 -0
img_remove_white_border ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import cv2
4
+ import numpy as np
5
+ import sys
6
+ import os
7
+
8
+ def remove_white_borders(image_path):
9
+ # Read the image
10
+ image = cv2.imread(image_path)
11
+
12
+ # Convert the image to grayscale
13
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
14
+
15
+ # Apply a binary threshold to get a binary image
16
+ _, binary = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)
17
+
18
+ # Invert the binary image
19
+ binary = cv2.bitwise_not(binary)
20
+
21
+ # Find contours in the binary image
22
+ contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
23
+
24
+ # Get the bounding box of the largest contour
25
+ x, y, w, h = cv2.boundingRect(contours[0])
26
+
27
+ # Crop the image using the bounding box
28
+ cropped_image = image[y:y+h, x:x+w]
29
+
30
+ # Create the output path with the -cropped suffix
31
+ base, ext = os.path.splitext(image_path)
32
+ output_path = f"{base}-cropped.png"
33
+
34
+ # Save the cropped image in lossless PNG format
35
+ cv2.imwrite(output_path, cropped_image)
36
+
37
+ print(f"Cropped image saved as {output_path}")
38
+
39
+ if __name__ == "__main__":
40
+ if len(sys.argv) != 2:
41
+ print("Usage: python script.py <image_path>")
42
+ else:
43
+ image_path = sys.argv[1]
44
+ remove_white_borders(image_path)
45
+