[python] 11
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- import cv2
- # Захват изображения
- def capture_image(file_path):
- image = cv2.imread(file_path)
- img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- return image, img_gray
- # Предобработка изображения
- def preprocess_image(img_gray):
- ret, thresh = cv2.threshold(img_gray, 120, 255, cv2.THRESH_BINARY)
- return thresh
- # Сегментация изображения
- def segment_image(thresh):
- contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
- return contours
- # Извлечение признаков
- def extract_features(contours):
- total_points = -4
- for contour in contours:
- epsilon = 0.0012 * cv2.arcLength(contour, True)
- approx = cv2.approxPolyDP(contour, epsilon, True)
- total_points += len(approx)
- return total_points
- # Обнаружение дефектов
- def detect_defects(total_points):
- if total_points < 20:
- return "Это брак: меньше 20 точек"
- elif total_points > 20:
- return "Это брак: больше 20 точек"
- else:
- return "Нормальная деталь"
- # Основной алгоритм работы системы
- def main(file_path):
- image, img_gray = capture_image(file_path)
- thresh = preprocess_image(img_gray)
- contours = segment_image(thresh)
- total_points = extract_features(contours)
- result = detect_defects(total_points)
- print("Количество точек:", total_points)
- print(result)
- # Визуализация контуров и точек
- image_copy = image.copy()
- for contour in contours:
- epsilon = 0.0012 * cv2.arcLength(contour, True)
- approx = cv2.approxPolyDP(contour, epsilon, True)
- for point in approx:
- cv2.circle(image_copy, (point[0][0], point[0][1]), 2, (0, 255, 0), 2, cv2.LINE_AA)
- cv2.imshow('Points', image_copy)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
- # Пример использования
- file_path = 'lego1.png'
- main(file_path)
Editor
You can edit this paste and save as new: