# -*- coding: utf-8 -*-
"""
Created on Wed Jul 22 15:26:12 2020
@author: hello world!
"""
import cv2
import os
import matplotlib.pyplot as plt
import numpy as np
filepath = 'E:\imagedata'
imgpath = os.path.join(filepath, 'aa1.png')
img = cv2.imread(imgpath,0)
color_img=cv2.imread(imgpath)
blur = cv2.GaussianBlur(img,(5,5),0)
ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)#OTSU阈值分割
cv2.imshow('th',th3)
img, contours, hierarchy = cv2.findContours(th3,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
min_rect = cv2.minAreaRect(contours[0])
box = cv2.boxPoints(min_rect)#返回最小外接矩形的四个顶点坐标
centerx=int(sum(box[:,1])/4)#计算矩形中心x
centery=int(sum(box[:,0])/4)#计算矩形中心y
box = np.int0(box)#四个顶点坐标变为int型
cv2.drawContours(color_img,[box],0,(0,220,255),2)
##特别注意,读图的时候img[i,j]=255,表示把第i行,第j列的值设为255,
##画图的时候是按xy坐标来,opencv中从图像左上角开始,往右x增加,往下y增加
cv2.circle(color_img, (centery, centerx), 2, (0, 0,255), 2)#注意
cv2.imshow('mark',color_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 图像预处理
原图
转灰度图后,用gauss滤波器滤波,然后用OTSU阈值分割
blur = cv2.GaussianBlur(img,(5,5),0)
ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
- 找轮廓
img, contours, hierarchy = cv2.findContours(th3,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)#返回的contours为包含轮廓的列表,len(contours)返回轮廓数量,(在mark点搜索框内,应只有一个轮廓)
- 找轮廓最小外接矩形
min_rect = cv2.minAreaRect(contours[0])
box = cv2.boxPoints(min_rect)#返回最小外接矩形的四个顶点坐标
centerx=int(sum(box[:,1])/4)#计算最小外接矩形中心x
centery=int(sum(box[:,0])/4)#计算最小外接矩形中心y