import numpy as np
import cv2
thresh_value = 140
number = 0
def getpos(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
print("img x=%d,y=%d", x, y)
# 定义回调函数,此程序无需回调,所以Pass即可
def callback(object):
global thresh_value, roi, roi_copy, number
roi[:, :] = roi_copy[:, :]
thresh_value = cv2.getTrackbarPos('thresh', 'roi_gray')
ret, roi = cv2.threshold(roi_copy, thresh_value, 255, cv2.THRESH_BINARY)
cv2.imshow('roi_gray', roi)
cv2.imshow('roi_thresh', roi)
mask = np.ones((3, 1), np.uint8)
roi_close = cv2.morphologyEx(roi, cv2.MORPH_OPEN, mask, iterations=1)
cv2.imshow('roi_close', roi_close)
roi_new = np.zeros((roi.shape[0] * 2, roi.shape[1] * 2), np.uint8)
roi_new[50:(50 + roi_close.shape[0]), 50:(50 + roi_close.shape[1])] = roi_close[:, :]
cv2.imshow('roi_new', roi_new)
mask_image, contours, hierarchy = cv2.findContours(roi_new, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
print("轮廓数量=", len(contours))
if len(contours) < 6:
print("不合格")
mask_image = cv2.cvtColor(mask_image, cv2.COLOR_GRAY2BGR)
cv2.drawContours(mask_image, contours, -1, (0, 0, 255), 1)
# 计算所有轮廓面积
area = []
# 找到最大的轮廓
number = 0
for k1 in range(len(contours)):
area.append(cv2.contourArea(contours[k1]))
if 600 < area[k1] < 900:
number += 1
print("所有轮廓面积为", area)
if number == 3:
print("合格")
else:
print("不合格")
max_idx1 = np.argmax(np.array(area))
for i in contours:
x, y, w, h = cv2.boundingRect(i) # 画矩形框
cv2.rectangle(mask_image, (x, y), (x + w, y + h), (0, 255, 0), 1)
cv2.imshow("mask_image", mask_image)
pass
def main():
global img, roi, roi_copy
global thresh_value
number =0
img = cv2.imread('handiantu.jpg')
img = cv2.resize(img, (round(img.shape[1]/2), round(img.shape[0]/2)))
cv2.imshow('img', img)
cv2.setMouseCallback('img', getpos)
dst = img.copy()
roi = dst[385:405, 315:373]
#roi = dst[293:312, 353:407]
roi = cv2.resize(roi, None, fx=4, fy=4)
cv2.imshow('roi', roi)
roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
roi = cv2.GaussianBlur(roi, (3, 3), 0, 0)
cv2.imshow('roi_gray', roi)
roi_copy = np.zeros((roi.shape[0], roi.shape[1]), np.uint8)
roi_copy[:, :] = roi[:, :]
cv2.createTrackbar('thresh', 'roi_gray', thresh_value, 255, callback)
#ret, roi = cv2.threshold(roi, 150, 255, cv2.THRESH_BINARY)
print(img.shape)
cv2.waitKey(0)
if __name__ =="__main__":
main()```
利用面积周长焊点判断
最新推荐文章于 2024-07-21 17:06:54 发布