C#命令行执行Python脚本
一、环境
1. 软件环境
Anaconda
PyCharm
Visual Studio 2015
2. Python环境
opencv_python
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv_python
matplotlib
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib
二、Python代码
"""
@Time:2022/3/21 16:01
@Author: shujin sun
@Desc: 缺陷检测测试
"""
import cv2 as cv
import numpy as np
import matplotlib. pyplot as plt
import math
import sys
plt. rcParams[ 'font.sans-serif' ] = [ 'SimHei' ]
plt. rcParams[ 'axes.unicode_minus' ] = False
class DetectDefect :
def __init__ ( self) :
self. little_img_file = ''
self. big_img_file = ''
self. big_img = np. array( 0 )
self. little_img = np. array( 0 )
self. roi_img = np. array( 0 )
self. bw_img = np. array( 0 )
self. w = 0
self. h = 0
self. roi_rect = [ 0 , 0 , 0 , 0 ]
self. roi_patchs = [ ]
self. thresh_value = 3000
self. match_methods = [ 'cv.TM_CCOEFF' ,
'cv.TM_CCOEFF_NORMED' ,
'cv.TM_CCORR' ,
'cv.TM_CCORR_NORMED' ,
'cv.TM_SQDIFF' ,
'cv.TM_SQDIFF_NORMED' ]
def set_little_image ( self, _file) :
self. little_img_file = _file
self. little_img = cv. imread( _file)
def set_big_image ( self, _file) :
self. big_img_file = _file
self. big_img = cv. imread( _file)
print ( self. big_img. shape)
self. h, self. w = self. big_img. shape[ : 2 ]
print ( 'big image shape: ' , self. w, self. h)
def set_thresh_value ( self, thresh_value) :
"""设置缺陷检测阈值门限"""
self. thresh_value = thresh_value
def conduct_edge ( self, src) :
'''边缘检测'''
gray_img = cv. cvtColor( src, cv. COLOR_BGR2GRAY)
median_intensity = np. median( gray_img)
lower_threshold = int ( max ( 0 , ( 1.0 - 0.33 ) * median_intensity) )
upper_threshold = int ( min ( 255 , ( 1.0 + 0.33 ) * median_intensity) )
canny_img = cv. Canny( gray_img, lower_threshold, upper_threshold)
plt. imshow( canny_img, cmap= 'gray' )
plt. title( 'canny edge detect result' )
plt. xticks( [ ] ) , plt. yticks( [ ] )
plt. show( )
def conduct_binary_adaptive ( self, src) :
"""二值化操作,自适应方法"""
src = cv. cvtColor( src, cv. COLOR_BGR2GRAY)
bw_img = cv. adaptiveThreshold( src,
255 ,
cv. ADAPTIVE_THRESH_MEAN_C,
cv. THRESH_BINARY,
5 ,
7 )
return bw_img
def conduct_binary ( self, src) :
"""二值化操作"""
src = cv. cvtColor( src, cv. COLOR_BGR2GRAY)
mean_intensity = np. mean( src)
median_intensity = np. median( src)
_, bw_img = cv. threshold( src, mean_intensity, 255 , cv. THRESH_BINARY_INV+ cv. THRESH_OTSU)
return bw_img
def match_template ( self, big, little) :
img = big. copy( )
idx = 3
print ( '选择的匹配算法:' , self. match_methods[ idx