Location>code7788 >text

The way C# calls Python scripts (I), using PaddleOCR-GUI as an example

Popularity:473 ℃/2024-12-15 01:31:13

preamble

Each language has the advantages of each language, Python due to its powerful ecology, many tasks can be achieved by calling the package, then it is important to learn to call Python scripts from C# projects to complete the task.C# call Python code in a variety of ways, if the Python side of the content is more, you can consider starting a Web Api for the call, if it's just a If it is just a simple script and does not need to be called frequently, then you can consider using the Process class to create a process to call, if there are several methods and need to interact with data, and may be called frequently, then you can consider using pythonnet.

Today, relying on the PaddleOCR-GUI project, first introduced to you is the C# call Python script way one: use the Process class to call Python script.

Background

PaddleOCR is an open source text recognition tool based on the PaddlePaddle framework, maintained by the Baidu team. It provides a full-process text recognition solution from pre-processing, text detection, text recognition to post-processing.PaddleOCR not only has excellent performance, but also flexible configuration, easy to use, to meet the needs of a variety of scenarios of text recognition, is widely used in advertising detection, image search, automated driving, content security audits and other fields.

image-20241213190225955

GitHub Address:/PaddlePaddle/PaddleOCR

It was also previously described that PaddleSharp can be called directly in C#:

C# using PaddleOCR for image text recognition

But you can't expect all the Python stuff to be encapsulated for you by the big guys so you can just tune it. Need to get out of your comfort zone and learn more about other languages other ecosystems.

PaddleOCR-GUI just gives PaddleOCR a simple interface to use, the use of the effect is shown below:

image-20241213191129075

image-20241213190922590

GitHub Address:/Ming-jiayou/PaddleOCR-GUI

You need to set up the PaddleOCR environment on your computer first:

Python version 3.12.8

Create a Python virtual environment and install PaddleOCR in the virtual environment, you can refer to the official website for a quick start:

Quick Start - PaddleOCR Documentation

C# Calling Python Scripts

Today's demonstration is to call a Python script through the Process class, and in conjunction with a real project, the thing to think about is how to do the passing of parameters? For example, the image path selected here and the language selected.

It can be used by means of command line arguments, and the Python script is written as shown below:

import sys
import logging
from paddleocr import PaddleOCR

# Paddleocr currently supports multiple languages that can be switched by modifying the lang parameter.
# e.g. `ch`, `en`, `fr`, `german`, `korean`, `japan`.

# Check if parameters are passed
if len() > 1.
imagePath = [1]
selectedLanguage = [2]
else.
print("Please provide full parameters")

# Configure the logging level to WARNING so that DEBUG and INFO level log messages are hidden.
(level=)

# Create a custom log handler that outputs logs to NullHandler (no output)
class NullHandler(): def emit(self, record)
class NullHandler(): def emit(self, record).
pass

# Get the logger for PaddleOCR
ppocr_logger = ('ppocr')

# Remove all default log handlers
for handler in ppocr_logger.handlers[:].
ppocr_logger.removeHandler(handler)

# Add a custom NullHandler
ppocr_logger.addHandler(NullHandler())

ocr = PaddleOCR(use_angle_cls=True, lang=selectedLanguage) # need to run only once to download and load model into memory
img_path = imagePath
result = (img_path, cls=True)
for idx in range(len(result)): res = result[idx].
res = result[idx]
for line in res: print(line[1][0])
print(line[1][0])

Parameters to be passed are passed here on the command line:

# Check if parameters are passed
if len() > 1:: imagePath = [1]: imagePath = [1].
imagePath = [1]
selectedLanguage = [2]
else.
print("Please provide full parameters")

Then in C# just use it like this:

  private Task ExecuteOCRCommand()
  {
      return (() =>
      {
          string selectedLanguage;
          switch (SelectedLanguage)
          {
              case "中文":
                  selectedLanguage = "ch";
                  break;
              case "English (language)":
                  selectedLanguage = "en";
                  break;
              default:
                  selectedLanguage = "ch";
                  break;
          }
          if ( == null || == null)
          {
              return;
          }
          string pythonScriptPath = ; // Replace yourPythonScript Path
          string pythonExecutablePath = ; // Replace yourPythonInterpreter path

          if (SelectedFilePath == null)
          {
              return;
          }

          string arguments = SelectedFilePath; // Replace it with the parameter you want to pass

          // Create a ProcessStartInfo an actual example
          ProcessStartInfo start = new ProcessStartInfo();
           = pythonExecutablePath;
           = $"\"{pythonScriptPath}\" {arguments} {selectedLanguage}";
           = false;
           = true;
           = true;

          // Create and start the process
          using (Process process = (start))
          {
              using ( reader = )
              {
                  string result = ();
                  OCRText = result;
              }
          }
      });
  }

The areas that need attention are these:

image-20241213192910898

The Python interpreter path is the Python interpreter in the virtual environment, which I have shown below here:

image-20241213193105587

image-20241213193142433

Pass in the Python script path with the set parameters here.

The above is the first way to call Python scripts in C# shared today, and the second way will be introduced in the next issue. Both ways are used in the project, and if you are interested, you can get the source code from GitHub for hands-on learning.