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()