#๐Ÿ”’ Removing Background Contrast

16 messages ยท Page 1 of 1 (latest)

delicate atlasBOT
#

@primal yacht

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

primal yacht
#

Hi everyone,

I'm working on a project where I need to remove the contrast in the background of an image while keeping the main contours intact. The current approach Iโ€™m using enhances the contrast, but Iโ€™m looking for a way to smooth out the background or make it uniform without affecting the foreground details.

If anyone has suggestions or knows of a method to do this effectively, I'd appreciate your help! Thank you in advance.

#
import cv2
import svgwrite
import os
import numpy as np

def image_to_svg(image_path, output_path, use_adaptive_threshold=True, canny_thresholds=(50, 150), visualize=False):
    """
    Converts an image to an SVG file with enhanced contour detection and provides detailed 
    information about the process in the terminal.
    
    :param image_path: Path to the input image.
    :param output_path: Path to the output SVG file.
    :param use_adaptive_threshold: Use adaptive thresholding for better detail.
    :param canny_thresholds: Tuple with thresholds for the Canny edge detector.
    :param visualize: Display the contours directly in a window.
    """
    # Check if the file exists
    if not os.path.exists(image_path):
        raise FileNotFoundError(f"The image '{image_path}' was not found.")
    
    print(f"[INFO] Loading image: {image_path}")
    img = cv2.imread(image_path)

    if img is None:
        raise ValueError(f"The image '{image_path}' could not be loaded.")

    # Convert color images to grayscale
    if len(img.shape) == 3:
        print("[INFO] Image is colored, converting to grayscale...")
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    else:
        img_gray = img

    # Image preprocessing: Apply median filter to reduce noise
    print("[INFO] Applying median filter to reduce noise...")
    img_blur = cv2.medianBlur(img_gray, 5)

    # Adjust histogram to improve contrast (optional)
    print("[INFO] Enhancing image contrast...")
    img_contrast = cv2.equalizeHist(img_blur)
#
    if use_adaptive_threshold:
        print("[INFO] Using adaptive thresholding...")
        binary = cv2.adaptiveThreshold(img_contrast, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                        cv2.THRESH_BINARY_INV, 11, 2)
    else:
        print(f"[INFO] Using Canny edge detector with thresholds: {canny_thresholds}...")
        binary = cv2.Canny(img_contrast, canny_thresholds[0], canny_thresholds[1])

    # Find contours
    print("[INFO] Finding contours in the image...")
    contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Check if contours were found
    if not contours:
        print("[WARNING] No contours found in the image!")
    else:
        print(f"[INFO] {len(contours)} contours found.")

    # Create SVG
    print(f"[INFO] Creating SVG file: {output_path}")
    dwg = svgwrite.Drawing(output_path, profile='tiny')
    for contour in contours:
        points = [(int(point[0][0]), int(point[0][1])) for point in contour]
        dwg.add(dwg.polygon(points, fill='none', stroke='black'))

    # Save SVG
    dwg.save()
    print("[INFO] SVG file saved successfully!")

    # Visualization (optional)
    if visualize:
        print("[INFO] Showing contours in a window...")
        img_contours = cv2.drawContours(img.copy(), contours, -1, (0, 255, 0), 1)
        cv2.imshow('Contours', img_contours)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    # Optional output as PNG
    png_output = os.path.splitext(output_path)[0] + '_contours.png'
    print(f"[INFO] Saving contours as PNG: {png_output}")
    img_contours = cv2.drawContours(img.copy(), contours, -1, (0, 255, 0), 1)
    cv2.imwrite(png_output, img_contours)
    print("[INFO] PNG file saved successfully!")
#

# Example call of the function with extended options
image_to_svg(
    image_path='input.jpg',           # Path to input image
    output_path='output.svg',         # Path to output SVG
    use_adaptive_threshold=True,      # Use adaptive thresholding
    canny_thresholds=(50, 150),       # Thresholds for Canny (only if adaptive_threshold=False)
    visualize=True                    # Show contours
)
#

These is my sample:

#

This is the output:

fleet ravine
#

Is it possible to identify the background by eliminating contours which don't join up? It looks a bit like the contours on the background have endpoints, which don't form closed curves. If you can eliminate them maybe that gets you the background area (outside the remaining contours) and then you can smooth that region or regions? Just thinking out loud here.

frail estuary
# primal yacht

This is one of those cases where AI is an excellent solution

primal yacht
#

I want the outlines to get an svg to 3D print

delicate atlasBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.