Das Bild schneiden, indem die weißen Räume entfernt werden
Posted: 31 Jan 2025, 13:13
Ich versuche, die leeren Räume im Bild zu identifizieren, und wenn es kein Bild gibt, möchte ich es aufnehmen, indem ich die Räume beseitigt. Genau wie in den folgenden Bildern. Img Alt = "Bild nach dem Schnitt" src = "https://i.static.net/fycj5krv.jpg"/>
Ich wäre dankbar für Ihre Hilfe. Vielen Dank im Voraus! < /P>
Ich habe den folgenden Code verwendet, aber nicht wirklich funktioniert.
Beispiel Verwendung:
Image_path = '/mnt/data/untitled.png' # Update mit Ihrem Dateipfad
cropped_image = crop_empty_spaces_refined (Image_Path, Threshold_percentage = 0,0001) # Versuchen Sie einen sehr kleinen Schwellenwert
Wenn Cropped_image nicht ist, ist keine:
cv2.imwrite('/mnt/data/cropped_output.png ', Cropped_image )
print ("Bild geschnitten und gespeichert")
else:
print ("konnte nicht pagen") < /p>
Ich wäre dankbar für Ihre Hilfe. Vielen Dank im Voraus! < /P>
Ich habe den folgenden Code verwendet, aber nicht wirklich funktioniert.
Code: Select all
import cv2
< /code>
Importieren Sie Numpy als np < /p>
Def crop_empty_spaces_refined (Image_Path, Threshold_percentage = 0.01):
Image = Cv2.imread (Image_path, CV2. Imread_unchanged) < /p>
if image is None:
print(f"Error: Could not read image at {image_path}")
return None
if image.shape[2] == 4: # RGBA image
gray = image[:, :, 3] # Use alpha channel
else:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
kernel = np.ones((3, 3), np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
image_area = image.shape[0] * image.shape[1]
min_contour_area = image_area * threshold_percentage
valid_contours = [cnt for cnt in contours if cv2.contourArea(cnt) >= min_contour_area]
if valid_contours:
# ***Corrected Bounding Box Calculation***
x_coords = []
y_coords = []
for cnt in valid_contours:
x, y, w, h = cv2.boundingRect(cnt)
x_coords.extend([x, x + w]) # Add both start and end x
y_coords.extend([y, y + h]) # Add both start and end y
x_min = min(x_coords)
y_min = min(y_coords)
x_max = max(x_coords)
y_max = max(y_coords)
cropped_image = image[y_min:y_max, x_min:x_max]
return cropped_image
else:
print("No valid contours found after filtering. Returning original image.")
return image
else:
return image
Image_path = '/mnt/data/untitled.png' # Update mit Ihrem Dateipfad
cropped_image = crop_empty_spaces_refined (Image_Path, Threshold_percentage = 0,0001) # Versuchen Sie einen sehr kleinen Schwellenwert
Wenn Cropped_image nicht ist, ist keine:
cv2.imwrite('/mnt/data/cropped_output.png ', Cropped_image )
print ("Bild geschnitten und gespeichert")
else:
print ("konnte nicht pagen") < /p>