python实现统计图片中物品的数量

下面代码有chatgpt完成, 粗略统计一个照片中物品的数量

import cv2
import os

def count_icons_in_image(image_path, debug_folder, threshold=200, min_icon_area=50):
    """
    Count the number of icons in an image by detecting contours of non-background areas.
    Save the processed image with contours drawn to a debug folder.

    Parameters:
    - image_path: str, path to the image file.
    - debug_folder: str, path to the folder where debug images will be saved.
    - threshold: int, threshold for background color (default is 200, suitable for white backgrounds).
    - min_icon_area: int, minimum area to consider a contour as an icon.

    Returns:
    - count: int, number of icons detected in the image.
    """
    # Load the image
    image = cv2.imread(image_path)

    # Convert the image to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Apply a binary threshold to isolate non-background areas
    _, thresh = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY_INV)

    # Apply a Gaussian blur to reduce noise
    blurred = cv2.GaussianBlur(thresh, (5, 5), 0)

    # Apply morphological operations to reduce noise
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    morph = cv2.morphologyEx(blurred, cv2.MORPH_CLOSE, kernel)

    # Find contours in the morphologically processed image
    contours, _ = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Filter out small contours based on area and draw them on the image
    icons_count = 0
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > min_icon_area:
            icons_count += 1
            # Draw the contour on the image
            cv2.drawContours(image, [cnt], -1, (0, 255, 0), 2)  # Green contour

    # Save the debug image with contours
    debug_image_path = os.path.join(debug_folder, os.path.basename(image_path))
    cv2.imwrite(debug_image_path, image)

    return icons_count

def count_icons_in_folder(folder_path, threshold=200, min_icon_area=50):
    """
    Count icons in all images in a folder, print the result, and save debug images.

    Parameters:
    - folder_path: str, path to the folder containing images.
    - threshold: int, threshold for background color (default is 200, suitable for white backgrounds).
    - min_icon_area: int, minimum area to consider a contour as an icon.
    """
    # Create a debug folder to save processed images
    debug_folder = os.path.join(folder_path, 'debug')
    os.makedirs(debug_folder, exist_ok=True)

    # Get a list of all files in the folder
    files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]

    for file_name in files:
        file_path = os.path.join(folder_path, file_name)

        try:
            # Count icons in the image
            count = count_icons_in_image(file_path, debug_folder, threshold, min_icon_area)
            print(f"Image: {file_name}, Icons found: {count}")
        except Exception as e:
            print(f"Error processing {file_name}: {e}")

# Define the path to the folder containing images
folder_path = '/Users/meican/Downloads/src/'

# Count icons in all images in the folder
count_icons_in_folder(folder_path)


# Define the path to the folder containing images
folder_path = '/Users/meican/Downloads/src'

# Count icons in all images in the folder
count_icons_in_folder(folder_path)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容