[Python] Converting Contour Pixel Coordinates to Paired Date and Dollar Series Using Python...

Discussão em 'Python' iniciado por Stack, Fevereiro 21, 2025.

  1. Stack

    Stack Membro Participativo

    Problem: Write a python function that inputs an image (.png file) to analyze its content to obtain pixel coordinate information before converting the pixel coordinates into date and dollar values in an array. How do I relate the x pixel coordinate element to the time scale on the image's x-axis and the y pixel coordinate element to the cost value on the image's y-axis? I do not know how to automatically generate the $/pixel conversion factor. Ultimately, I am trying to re-create the image (.png file) in excel once I have the x and y pixel coordinate information converted into time and cost values in a series. Please use the .png I uploaded for this post to run it through my code to see where I am stuck in the development process.

    .png File Test Artifact [​IMG]

    import cv2 as vision
    import numpy as np


    extracted_image = r"filepath..." # as .png

    # load the cumulative spend plan image
    image = vision.imread(extracted_image)

    if image is None:
    print("Error: could not load image. Check file path.")
    exit()

    # convert to HSV color space
    hsv_image = vision.cvtColor(image, vision.COLOR_BGR2HSV)
    lower_bound = np.array([0,0,0])
    upper_bound = np.array([50,50,50])
    mask = vision.inRange(hsv_image, lower_bound, upper_bound)

    # find contours
    contours, _ = vision.findContours(mask, vision.RETR_EXTERNAL, vision.CHAIN_APPROX_SIMPLE)

    # intialize
    black_contour = None

    if contours:
    black_contour = max(contours, key=vision.contourArea) # use the largest contour if multiple found

    # visualize whether contour was found
    if black_contour is not None:
    # draw on top of black contour
    vision.drawContours(image, [black_contour], -1, (0,0,255), 2)

    # get the coordinates of the black contur points
    coordinates = black_contour[:,0,:] # get x,y coordinates
    print("Coordinates of black contour in pixels:")
    for (x,y) in coordinates:
    print(f"({x}, {y})")
    else:
    print("Non black contour found.")


    vision.imshow("Cumulative Spend Plan", image)
    vision.waitKey(0)
    vision.destroyAllWindows()

    Continue reading...

Compartilhe esta Página