1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/harry-fan-chip-defect-detection

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
В этом репозитории не указан файл с открытой лицензией (LICENSE). При использовании обратитесь к конкретному описанию проекта и его зависимостям в коде.
Клонировать/Скачать
recoding.py 5.6 КБ
Копировать Редактировать Web IDE Исходные данные Просмотреть построчно История
HarryFan Отправлено 08.06.2021 06:40 158993b
# -*- coding:utf-8 -*-
import cv2
import os
import sys
import numpy as np
# 制作模板的图像路径
ORI_IMAGE_PATH = r'mm12.jpg'
# 待检测图像的路径
DETECT_IMAGE_PATH = r'mm11.jpg'
def rotate_bound(image, angle):
# grab the dimensions of the image and then determine the
# center
(h, w) = image.shape[:2]
(cX, cY) = (w // 2, h // 2)
# grab the rotation matrix (applying the negative of the
# angle to rotate clockwise), then grab the sine and cosine
# (i.e., the rotation components of the matrix)
M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
# compute the new bounding dimensions of the image
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
# adjust the rotation matrix to take into account translation
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
# perform the actual rotation and return the image
return cv2.warpAffine(image, M, (nW, nH))
def main(img_cap):
# 读取制作模板和待检测的原图
kernel = np.ones((5,5),np.uint8)
img_ori = cv2.imread(ORI_IMAGE_PATH)
img_detect = cv2.imread(DETECT_IMAGE_PATH)
# img_detect = img_cap
# 灰度化并保存
gray_img_ori = cv2.cvtColor(img_ori, cv2.COLOR_BGR2GRAY)
gray_img_detect = cv2.cvtColor(img_detect, cv2.COLOR_BGR2GRAY)
cv2.imwrite('mm_gray_mm11.png', gray_img_detect)
cv2.imwrite('mm_gray_mm12.png', gray_img_ori)
# 制作模板:
# 先检测出待检测的目标,阈值-寻找轮廓-寻找最小正包围框的WH
# 待检测模板可以用最小旋转包围框来确定旋转角度
# 在按同样的步骤制作模板,只是最后一步采用最小旋转包围框,并
ret, det_thresh_img = cv2.threshold(
gray_img_detect, 40, 255, cv2.THRESH_BINARY)#二值化
image_contours,det_image, hierarchy = cv2.findContours(
det_thresh_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)#找方框
image_contours_mask=cv2.erode(image_contours,kernel,iterations=1)
contour_len_det = [len(x) for x in det_image] #方框个数
print('contour_size',contour_len_det)
max_contor_det = det_image[np.argmax(contour_len_det)]
x, y, w, h = cv2.boundingRect(max_contor_det)
det_rect = cv2.minAreaRect(max_contor_det)
det_box = cv2.boxPoints(det_rect)
# normalize coordinates to integers
det_box = np.int0(det_box)
# 旋转模板,和目标角度一致
rotation_angel = det_rect[-1]
rows,cols = image_contours_mask.shape[:2]
#第一个参数旋转中心,第二个参数旋转角度,第三个参数:缩放比例
M = cv2.getRotationMatrix2D(det_rect[0],rotation_angel,1)
#第三个参数:变换后的图像大小
print('rows',rows,cols)
res = cv2.warpAffine(image_contours_mask,M,(cols,rows))
res_det = cv2.warpAffine(gray_img_detect,M,(cols,rows))
# # 目标旋转角度 53.1°
print('rot_ang',rotation_angel)
image_contours_det_rot,contour_rot_det, hierarchy_rot = cv2.findContours(
res, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contour_len_rot = [len(x) for x in contour_rot_det]
max_contor_rot = contour_rot_det[np.argmax(contour_len_rot)]
rect_rot = cv2.minAreaRect(max_contor_rot)
# calculate coordinates of the minimum area rectangle
box_rot = cv2.boxPoints(rect_rot)
# normalize coordinates to integers
box_rot = np.int0(box_rot)
# 裁剪ROI区域
print('box_rot',box_rot)
box = box_rot
x_min = min(box[:,1])
x_max = max(box[:,1])
y_min = min(box[:,0])
y_max = max(box[:,0])
gray_rot_img = gray_img_ori[x_min:x_max, y_min:y_max]
det_rot_img = res_det[x_min:x_max, y_min:y_max]
cv2.imwrite('mm_gray_rot_img.png', gray_rot_img)
# 制作模板的步骤
ret, thresh_img = cv2.threshold(gray_img_ori, 50, 255, cv2.THRESH_BINARY)
image_contours_ori,contour_ori, hierarchy = cv2.findContours(
thresh_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contour_len = [len(x) for x in contour_ori]
max_contor = contour_ori[np.argmax(contour_len)]
rect = cv2.minAreaRect(max_contor)
# calculate coordinates of the minimum area rectangle
box = cv2.boxPoints(rect)
# normalize coordinates to integers
box = np.int0(box)
# 裁剪ROI区域
print('bos_ori',box)
x_min = min(box[:,1])
x_max = max(box[:,1])
y_min = min(box[:,0])
y_max = max(box[:,0])
gray_roi_img = gray_img_ori[x_min:x_max, y_min:y_max]
gray_roi_img_cut = image_contours_ori[x_min:x_max, y_min:y_max]
cv2.imwrite('mm_gray_roi_img.png', gray_roi_img)
cv2.imwrite('gray_roi_img_cut.png', gray_roi_img_cut)
# 旋转模板,和目标角度一致
gray_roi_img_cut=cv2.dilate(gray_roi_img_cut,kernel,iterations=1)
gray_rot_img=cv2.dilate(gray_rot_img,kernel,iterations=1)
ch, cw = gray_rot_img.shape[:2]
gray_roi_img_cut = cv2.resize(gray_roi_img_cut, (cw, ch))
both = gray_roi_img_cut - gray_rot_img
both=cv2.dilate(both,kernel,iterations=2)
image_contours_both,contour_both, hierarchy_both = cv2.findContours(
both, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(det_rot_img, contour_both, -1, (255,0,255), 2)
try:
image_contours_mask = cv2.resize(image_contours_mask, (640,480))
cv2.imshow('image_contours_mask', image_contours_mask)
except Exception as e:
print('Error: !', e)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
# main()中主要做了模板匹配的操作,模板相减得到污染物位置没有做
cap = cv2.VideoCapture(1)
cap.set(15, -10);
secuess,fream = cap.read()
main(fream)

Опубликовать ( 0 )

Вы можете оставить комментарий после Вход в систему

1
https://api.gitlife.ru/oschina-mirror/harry-fan-chip-defect-detection.git
git@api.gitlife.ru:oschina-mirror/harry-fan-chip-defect-detection.git
oschina-mirror
harry-fan-chip-defect-detection
harry-fan-chip-defect-detection
master