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

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

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
В этом репозитории не указан файл с открытой лицензией (LICENSE). При использовании обратитесь к конкретному описанию проекта и его зависимостям в коде.
Клонировать/Скачать
templed_img.py 5.4 КБ
Копировать Редактировать 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_ori = cv2.imread(ORI_IMAGE_PATH)
img_detect = cv2.imread(DETECT_IMAGE_PATH)
# 灰度化并保存
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)#二值化
det_image, hierarchy = cv2.findContours(
det_thresh_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)#找方框
# x, y, w, h = cv2.boundingRect(det_image[1])
# cv2.rectangle(gray_img_detect, (x,y), (x+w,y+h), (0,0,255), 5)
# cv2.imshow("1111",gray_img_detect)
# cv2.waitKey()
# 画轮廓
# det_img_new = cv2.drawContours(img_detect, det_image, -1, (0, 0, 255), 3)
# 计算最小旋转矩形包围框
contour_len_det = [len(x) for x in det_image] #方框个数
print(contour_len_det)
max_contor_det = det_image[np.argmax(contour_len_det)]
x, y, w, h = cv2.boundingRect(max_contor_det)
# det_img_new = cv2.drawContours(img_detect, max_contor, -1, (0, 0, 255), 3)
det_rect = cv2.minAreaRect(max_contor_det)
# 目标旋转角度 53.1°
rotation_angel = det_rect[-1]
# # calculate coordinates of the minimum area rectangle
# det_box = cv2.boxPoints(det_rect)
# # normalize coordinates to integers
# det_box = np.int0(det_box)
# bounding = cv2.rectangle(img_detect, (x, y), (x+w, y+h), (255, 0, 255), 2)
# det_img = cv2.polylines(img_detect, [det_box], True, (255, 0, 255), 3)
# 制作模板的步骤
ret, thresh_img = cv2.threshold(gray_img_ori, 50, 255, cv2.THRESH_BINARY)
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)]
# img_new = cv2.drawContours(img_ori, max_contor, -1, (0, 0, 255), 3)
rect = cv2.minAreaRect(max_contor)
# calculate coordinates of the minimum area rectangle
box = cv2.boxPoints(rect)
# normalize coordinates to integers
box = np.int0(box)
# tuple(box[0])
# new_roi = cv2.rectangle(img_ori, tuple(box[1]), tuple(box[-1]), (0, 255, 0), 2)
# roi_img = img_ori[box[1, 1]:box[0, 1], box[1, 0]:box[2, 0]]
# 裁剪ROI区域
# gray_roi_img = gray_img_ori[min(box[:, 1]):max(
# box[:, 1]), min(box[:, 1]):max(box[:, 1])]
print('box:')
print(box)
# cv2.imshow("1", gray_img_ori)
# cv2.waitKey()
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[box[1, 1]:box[2, 1], box[0, 0]:box[1, 0]]
gray_roi_img = gray_img_ori[x_min:x_max, y_min:y_max]
cv2.imwrite('mm_gray_roi_img.png', gray_roi_img)
# ret, thresh_img = cv2.threshold(gray_img_ori,50, 255, cv2.THRESH_BINARY)
# cv2.rectangle()
# gray_roi = cv2.imread(r'mm_gray_roi_img.png')
# temple_img = cv2.imread(r'mm_gray_mm11.png')
# 旋转模板,和目标角度一致
temple = rotate_bound(gray_roi_img, rotation_angel)
# 不resize结果不准确,resize后也不太准确,自己取舍
temple = cv2.resize(temple, (w, h))
th, tw = temple.shape[:2]
# temple_img = cv2.imread(r'mm_gray_mm11.png')
# 模板匹配
result = cv2.matchTemplate(gray_img_detect, temple, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
tl = max_loc
br = (tl[0]+tw, tl[1]+th)
# 画框框
_ = cv2.rectangle(gray_img_detect, tl, br, (0, 0, 255), 2)
templed_img_gary = gray_img_detect[tl[-1]:br[-1], tl[0]:br[0]]
cv2.imwrite('mm_templed_gray.png', templed_img_gary)
# cv2.namedWindow('img', 1)
# try:
# cv2.imshow('templed_img', templed_img_gary)
# cv2.imshow('temple_img', temple)
# cv2.imshow('gray_roi_img', gray_roi_img)
# except Exception as e:
# print('Error: !', e)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
if __name__ == '__main__':
# main()中主要做了模板匹配的操作,模板相减得到污染物位置没有做
main()

Опубликовать ( 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