在图像中查找吉他拨片

问题描述 投票:0回答:0

Starting image 我已经尝试了书中的所有方法来让这个脚本在这张图片中准确地找到 14 个吉他拨片。

import cv2
from PIL import Image
import numpy as np
from google.colab.patches import cv2_imshow
# Load image using PIL
image = Image.open("guitar_picks.jpeg")

# Convert PIL image to OpenCV format
img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)

# Preprocess image for contrast
clip_limit = 2.0
tile_size = (8,8)
while True:
    # Convert image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply Contrast Limited Adaptive Histogram Equalization (CLAHE) to grayscale image
    clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_size)
    img_clahe = clahe.apply(gray)

    # Apply noise reduction
    blur = cv2.GaussianBlur(img_clahe, (5, 5), 0)

    # Perform image segmentation
    thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
    cnts, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cv2_imshow(thresh)
    # Detect circles in the thresholded image
    circles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, dp=1, minDist=20, param1=50, param2=30, minRadius=5, maxRadius=30)

    # If circles are detected, draw them on the original image
    if circles is not None:
      circles = np.round(circles[0, :]).astype("int")
      for (x, y, r) in circles:
        cv2.circle(img, (x, y), r, (0, 255, 0), 2)


    # Filter contours by size to eliminate noise and non-pick objects
    filtered_cnts = []
    for c in cnts:
        x,y,w,h = cv2.boundingRect(c)
        area = w * h
        if area > 500 and area < 5000:
            filtered_cnts.append(c)

    # Update number of picks found
    num_picks = len(filtered_cnts)

    # Draw contours on original image
    for c in filtered_cnts:
        cv2.drawContours(img, [c], -1, (0, 0, 255), 2)

    # Display the results
    cv2_imshow(img)
    cv2.waitKey(0)

    # Check if 14 guitar picks are found
    if num_picks == 14:
        print("14 guitar picks found!")
        # Save the image of highlighted guitar picks
        img_highlighted = img.copy()
        for c in filtered_cnts:
         cv2.drawContours(img_highlighted, [c], -1, (0, 0, 255), 2)
         cv2.imwrite("highlighted_guitar_picks.jpeg", img_highlighted)
         finale = Image.open("highlighted_guitar_picks.jpeg")
        break

    # If fewer than 14 picks are found, adjust the contrast and try again
    elif num_picks < 14:
        # Increase the clip limit for the Contrast Limited Adaptive Histogram Equalization (CLAHE)
        clip_limit += 0.5
        print(f"Trying new clip limit: {clip_limit}")
        if clip_limit > 5.0:
            print("Could not find 14 guitar picks with current settings.")
            break

    # If more than 14 picks are found, reduce the clip limit and try again
    else:
        # Decrease the clip limit for the Contrast Limited Adaptive Histogram Equalization (CLAHE)
        clip_limit -= 0.5
        print(f"Trying new clip limit: {clip_limit}")
        if clip_limit < 0.5:
            print("Could not find 14 guitar picks with current settings.")
            break

# Destroy all windows
cv2.destroyAllWindows()

它会自动更改对比度值,并使用各种 OpenCV 组件来执行此操作。问题是,代码可以找到 14 个吉他拨片,但找不到正确的拨片。相反,我最终得到如下所示的输出结果:Output Result of the 14 found

即使在线打印阈值图像时,它也非常……有颗粒感。我试图对其进行降噪,但它不起作用。我在这上面花了 5 天时间,这让我绞尽脑汁。 我怎样才能挑出准确的 14 个吉他拨片?

python opencv object-detection
© www.soinside.com 2019 - 2024. All rights reserved.