传统图像处理识别check_box

import cv2
import numpy as np
import os

def preprocess_image(image_path):

    img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

    enhanced = cv2.equalizeHist(img)

    blurred = cv2.GaussianBlur(enhanced, (3, 3), 0)

    thresh = cv2.adaptiveThreshold(
        blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2
    )

    return thresh


def check_for_tick(preprocessed_image):


    contours, _ = cv2.findContours(preprocessed_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    detected = False

    for contour in contours:
        
        x, y, w, h = cv2.boundingRect(contour)
        area = cv2.contourArea(contour)
        mask = np.zeros(preprocessed_image.shape, dtype=np.uint8)
        cv2.drawContours(mask, [contour], -1, 255, -1)

        # 统计轮廓区域内白色像素点数量
        pixel_count = cv2.countNonZero(mask)

        print(f"轮廓边界框: x={x}, y={y}, w={w}, h={h}, 面积={area}, 像素点数量={pixel_count}")


        if 5 < w < 20 and 5 < h < 20 and 50 < area < 200 and 50 < pixel_count < 250:

            perimeter = cv2.arcLength(contour, True)
            approx = cv2.approxPolyDP(contour, 0.02 * perimeter, True)

            # 如果多边形有拐点(如对钩形状)
            if len(approx) >= 3:
                detected = True
                break

    return detected

if __name__ == "__main__":

    folder_path = "E:/test"


    image_files = [f for f in os.listdir(folder_path) if f.endswith(('.png', '.jpg', '.jpeg'))]

    for image_file in image_files:
        image_path = os.path.join(folder_path, image_file)


        preprocessed_img = preprocess_image(image_path)


        has_tick = check_for_tick(preprocessed_img)


        print(f"图像 {image_file}: {'选项框内有对钩!' if has_tick else '选项框内没有对钩!'}")


        contours, _ = cv2.findContours(preprocessed_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        img_with_contours = cv2.cvtColor(preprocessed_img, cv2.COLOR_GRAY2BGR)
        cv2.drawContours(img_with_contours, contours, -1, (0, 255, 0), 1)


        resized_img = cv2.resize(img_with_contours, (300, 300), interpolation=cv2.INTER_LINEAR)
        cv2.imshow(f"Detected Image - {image_file}", resized_img)
        cv2.waitKey(0)

    cv2.destroyAllWindows()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值