Skip to content

Commit

Permalink
初版
Browse files Browse the repository at this point in the history
  • Loading branch information
utopiat-ire committed Jun 6, 2022
1 parent 2440db8 commit 7ccdcdd
Show file tree
Hide file tree
Showing 14 changed files with 614 additions and 2 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2022 ゆうと
Copyright (c) 2022 utopiat.net

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
111 changes: 111 additions & 0 deletions OCR.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using System.Windows.Media.Imaging;
using Windows.Graphics.Imaging;
using Windows.Media.Ocr;
using System.Threading.Tasks;
using System.Drawing;

namespace Produire.PImaging
{
public class OCR : IProduireStaticClass
{
/// <summary>
/// 画像から文字認識します。
/// </summary>
/// <param name="image">読み取り画像</param>
/// <param name="lang">対象の言語</param>
/// <returns></returns>
[自分で]
public string 読み取る([]Image image, [として, 省略]string lang)
{
Task<SoftwareBitmap> t1 = null;
Task.Run(() =>
{
t1 = ConvertSoftwareBitmap((Bitmap)image);
}).Wait();
SoftwareBitmap x1 = t1.Result;

if (string.IsNullOrEmpty(lang)) lang = "ja-JP";

Task<OcrResult> t2 = null;
Task.Run(() =>
{
t2 = RunOcr(x1, lang);
}).Wait();
OcrResult x2 = t2.Result;
StringBuilder builder = new StringBuilder();
foreach (var line in x2.Lines)
{
if (builder.Length > 0) builder.AppendLine();
var words = line.Words;
bool lastHalf = false;
for (int i = 0; i < words.Count; i++)
{
var word = words[i];
bool isHalf = IsHalf(word.Text);
if (lastHalf != isHalf)
{
if (i > 0) builder.Append(" ");
}
builder.Append(word.Text);
}
}
return builder.ToString();
}

private bool IsHalf(string text)
{
bool half = true;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (char.IsDigit(c) || char.IsLower(c) || char.IsUpper(c) || char.IsWhiteSpace(c))
{
}
else
return false;
}
return half;
}

private async Task<SoftwareBitmap> ConvertSoftwareBitmap(Bitmap bitmap)
{
System.Windows.Media.Imaging.BitmapFrame bitmapSource = null;
using (var wfStream = new MemoryStream())
{
bitmap.Save(wfStream, System.Drawing.Imaging.ImageFormat.Bmp);
wfStream.Seek(0, SeekOrigin.Begin);
bitmapSource = System.Windows.Media.Imaging.BitmapFrame.Create(wfStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

SoftwareBitmap sbitmap = null;

using (MemoryStream wpfStream = new MemoryStream())
{
var encoder = new BmpBitmapEncoder();
encoder.Frames.Add(bitmapSource);
encoder.Save(wpfStream);

var irstream = WindowsRuntimeStreamExtensions.AsRandomAccessStream(wpfStream);

var decorder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(irstream);
sbitmap = await decorder.GetSoftwareBitmapAsync();
}

return sbitmap;
}

private async Task<OcrResult> RunOcr(SoftwareBitmap sbitmap, string lang)
{
OcrEngine engine = OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language(lang));
var result = await engine.RecognizeAsync(sbitmap);
return result;
}

}
}
156 changes: 156 additions & 0 deletions Produire.WRT.Imaging.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{866DDC73-35A5-449A-8AD9-41EE8627008B}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Produire.PImaging</RootNamespace>
<AssemblyName>Produire.WRT.Imaging</AssemblyName>
<StartupObject>
</StartupObject>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>ire-public.snk</AssemblyOriginatorKeyFile>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>
</DocumentationFile>
<PlatformTarget>AnyCPU</PlatformTarget>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>3</WarningLevel>
<DocumentationFile>
</DocumentationFile>
<PlatformTarget>AnyCPU</PlatformTarget>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="PresentationCore" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="Windows, Version=255.255.255.255, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>.\Windows.winmd</HintPath>
</Reference>
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="OCR.cs" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="bin\Debug\OCRサンプル.rdr" />
<None Include="ire-public.snk" />
<None Include="LICENSE" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<None Include="README.md" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows インストーラー 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Windows.SDK.Contracts">
<Version>10.0.19041.1</Version>
</PackageReference>
<PackageReference Include="System.Runtime.WindowsRuntime">
<Version>4.7.0</Version>
</PackageReference>
<PackageReference Include="System.Runtime.WindowsRuntime.UI.Xaml">
<Version>4.7.0</Version>
</PackageReference>
<PackageReference Include="utopiat.Produire">
<Version>1.8.1117</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Content Include="bin\Release\Produire.WRT.Imaging.dll" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<PropertyGroup>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
</Project>
25 changes: 25 additions & 0 deletions Produire.WRT.Imaging.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.271
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Produire.WRT.Imaging", "Produire.WRT.Imaging.csproj", "{866DDC73-35A5-449A-8AD9-41EE8627008B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{866DDC73-35A5-449A-8AD9-41EE8627008B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{866DDC73-35A5-449A-8AD9-41EE8627008B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{866DDC73-35A5-449A-8AD9-41EE8627008B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{866DDC73-35A5-449A-8AD9-41EE8627008B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {18909115-0E0F-497D-814A-B90F52EDB51E}
EndGlobalSection
EndGlobal
39 changes: 39 additions & 0 deletions Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Produire;

// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("イメージ処理プラグイン")]
[assembly: AssemblyDescription("イメージ処理に関する機能を利用できます")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("utopiat.net")]
[assembly: AssemblyProduct("日本語プログラミング言語プロデル")]
[assembly: AssemblyCopyright("Copyright(C) 2007-2022 utopiat.net")]
[assembly: AssemblyTrademark("プロデル")]
[assembly: AssemblyCulture("")]

[assembly: PluginName("イメージ処理プラグイン")]
[assembly: PluginDescription("イメージ処理に関する機能を利用できます")]
[assembly: PluginVersion("1.0")]
[assembly: PluginAcceptVersion("1.0")]

// ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントには
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]

// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("e4ff1509-3028-477c-b3af-e0d7722a3da5")]

// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Loading

0 comments on commit 7ccdcdd

Please sign in to comment.