C#命令行执行Python脚本

本文详细介绍了如何在C#环境中通过命令行执行Python脚本,涉及软件环境如Anaconda、PyCharm和Visual Studio 2015的配置,Python库opencv_python与matplotlib的使用,以及C#工程的实现过程,包括界面设计、功能代码实现,最终展示了运行结果和完整的项目代码。
摘要由CSDN通过智能技术生成

C#命令行执行Python脚本

一、环境

1. 软件环境

  1. Anaconda
  2. PyCharm
  3. Visual Studio 2015

2. Python环境

  1. opencv_python
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv_python
  1. matplotlib
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib

二、Python代码

# encoding: utf-8
"""
@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)

        # big image 的大小
        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)# cv.IMREAD_GRAYSCALE

    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.ADAPTIVE_THRESH_GAUSSIAN_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)
        # print('图像灰度均值、中值:', mean_intensity, median_intensity)
        _, 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()
        # eval函数,将字符串作为脚本代码来执行
        idx = 3  # 1 or 3方法效果最好
        print('选择的匹配算法:', self.match_methods[idx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值