import cv2 import numpy as np

Load image

img1 = cv2.imread('images/muban.png')

Convert to grayscale

img2 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)

Threshold image

ret, img3 = cv2.threshold(img2, 120, 255, cv2.THRESH_BINARY_INV)

Apply morphology operations

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) img4 = cv2.morphologyEx(img3, cv2.MORPH_OPEN, kernel) img5 = cv2.morphologyEx(img4, cv2.MORPH_OPEN, kernel)

Find contours

contours, hierarchy = cv2.findContours(img5, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

Draw contours

cv2.drawContours(img1, contours, 0, (0, 0, 255), 2) cv2.drawContours(img1, contours, 1, (0, 0, 255), 2)

Calculate area of contours

area = cv2.contourArea(contours[0]) + cv2.contourArea(contours[1])

Check for defects

if area > 200: print("这个零件有瑕疵,具体看红圈的部分") else: print("这个零件无瑕疵,可以通过质检")

Display images

cv2.imshow('muban', img5) cv2.imshow('gray', img1) cv2.waitKey(0

对下面代码进行优化import cv2 import numpy as np img1=cv2imreadimagesmubanpng img2=cv2cvtColorimq1cv2COLOR BGR2GRAY retimg3=cv2thresholdimg2120255cv2THRESH BINARY INV #img4=cv2adaptiveThresholdimg2255cv2ADAPTIV

原文地址: https://www.cveoy.top/t/topic/eO7M 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录