Слияние кода завершено, страница обновится автоматически
# -*- 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)
# 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_size',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)
det_box = cv2.boxPoints(det_rect)
# normalize coordinates to integers
det_box = np.int0(det_box)
# cv2.imshow("1", gray_img_ori)
# cv2.waitKey()
# 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')
# 旋转模板,和目标角度一致
rotation_angel = det_rect[-1]
# temple_det = rotate_bound(image_contours_mask, -rotation_angel)
# 不resize结果不准确,resize后也不太准确,自己取舍
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))
#temple_det = cv2.resize(temple_det, (w, h))
#th, tw = temple.shape[:2]
# gray_img_detect = temple_det[det_box[1, 1]:det_box[0, 1], det_box[1, 0]:det_box[2, 0]]
# cv2.imwrite('gray_img_detect.png', gray_img_detect)
# # 目标旋转角度 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)]
# img_new = cv2.drawContours(img_ori, max_contor, -1, (0, 0, 255), 3)
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)
# 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_rot',box_rot)
box = box_rot
# 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_rot_img = gray_img_ori[x_min:x_max, y_min:y_max]
#gray_rot_img = res[box_rot[1, 1]:box_rot[0, 1], box_rot[1, 0]:box_rot[2, 0]]
det_rot_img = res_det[x_min:x_max, y_min:y_max]
cv2.imwrite('mm_gray_rot_img.png', gray_rot_img)
# # 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)
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)]
# 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('bos_ori',box)
# cv2.imshow("1", gray_img_ori)
# cv2.waitKey()
# 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]
#gray_roi_img = gray_img_ori[box[1, 1]:box[0, 1], box[1, 0]:box[2, 0]]
#gray_roi_img_cut = image_contours_ori[box[1, 1]:box[0, 1], box[1, 0]:box[2, 0]]
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)
# 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')
# 旋转模板,和目标角度一致
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)
#temple = rotate_bound(gray_roi_img, rotation_angel)
# 不resize结果不准确,resize后也不太准确,自己取舍
#temple = cv2.resize(temple, (w, h))
#th, tw = temple.shape[:2]
#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]]
#3cv2.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', det_rot_img)
#cv2.imshow('det_rot_img', det_rot_img)
image_contours_mask = cv2.resize(image_contours_mask, (640,480))
cv2.imshow('image_contours_mask', image_contours_mask)
# cv2.imshow('image_contours_ori', gray_roi_img_cut)
# cv2.imshow('both', both)
# cv2.imshow('temple_det2', res)
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 )