Compare commits

..
Author SHA1 Message Date
luochen570 081a04de90 ci: rerun Windows release with token
Build Windows Release / Build Windows x64 Release (push) Successful in 1m26s
2026-05-30 21:40:03 +08:00
luochen570 e6405ad09d ci: fix PowerShell status interpolation
Build Windows Release / Build Windows x64 Release (push) Failing after 24s
2026-05-30 21:31:06 +08:00
luochen570 2968dd7caa ci: avoid cross-step env in Windows workflow
Build Windows Release / Build Windows x64 Release (push) Failing after 25s
2026-05-30 21:29:49 +08:00
luochen570 aa18669312 ci: package from fixed runner temp path
Build Windows Release / Build Windows x64 Release (push) Failing after 25s
2026-05-30 21:27:23 +08:00
luochen570 cffa806267 ci: use fixed source path across runner steps
Build Windows Release / Build Windows x64 Release (push) Failing after 24s
2026-05-30 21:16:55 +08:00
luochen570 37ee80e3e7 ci: avoid non-ascii PowerShell literals
Build Windows Release / Build Windows x64 Release (push) Failing after 15s
2026-05-30 21:02:23 +08:00
luochen570 ce5918e4c0 ci: make Windows workflow PowerShell 5 compatible
Build Windows Release / Build Windows x64 Release (push) Failing after -3s
2026-05-30 21:01:21 +08:00
luochen570 a2c9097496 ci: build Windows package without JS actions
Build Windows Release / Build Windows x64 Release (push) Failing after -3s
2026-05-30 20:59:11 +08:00
luochen570 1ff605bc91 ci: target registered Windows runner label
Build Windows Release / Build Windows x64 Release (push) Failing after 32s
2026-05-30 20:54:29 +08:00
luochen570 b0f8695a25 ci: build release on Windows runner
Build Windows Release / Build Windows x64 Release (push) Has been cancelled
2026-05-30 20:50:34 +08:00
luochen570 83ac7ada50 ci: use Linux runner for Windows release
Build Windows Release / Cross build Windows x86_64 Release (push) Has been cancelled
2026-05-30 20:44:24 +08:00
luochen570 56964d71fc ci: add Windows release workflow
Build Windows Release / Build Windows x64 Release (push) Has been cancelled
2026-05-30 20:41:46 +08:00
luochen570 fc9f66d56d docs: add Windows build instructions and script 2026-05-30 17:24:05 +08:00
luochen570 4627343e31 feat: add simplified Qt image viewer Dev branch 2026-05-30 17:18:55 +08:00
luochen570 4832838a0d ci: upload build outputs to repository release
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 0s
Build Windows Release with MSYS2 / build-windows-msys2 (push) Has been cancelled
2026-05-30 14:11:23 +08:00
luochen570 8f6152a382 ci: try uploading unsplit release package 2026-05-30 14:07:48 +08:00
luochen570 add0a6758e ci: use GitHub action steps on proxied runner 2026-05-30 14:06:14 +08:00
luochen570 796a2b7712 ci: add MSYS2 Windows release workflow
Cross Build Windows Release on Linux / cross-build-windows (push) Successful in 5m41s
Build Windows Release with MSYS2 / build-windows-msys2 (push) Has been cancelled
2026-05-30 13:36:59 +08:00
luochen570 8f4579f97c ci: split cross build package uploads
Cross Build Windows Release on Linux / cross-build-windows (push) Successful in 5m7s
2026-05-30 01:34:14 +08:00
luochen570 4e8b0d5f06 ci: use package secret for upload
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 5m30s
2026-05-30 01:22:11 +08:00
luochen570 f8449a5480 ci: use package token for Gitea upload
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m43s
2026-05-30 01:11:00 +08:00
luochen570 5c0f1a1409 ci: verify cross package checksum from output directory
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m48s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 01:04:21 +08:00
luochen570 4793f21f2b ci: fix Fedora mingw OpenCV include path
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m47s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 01:01:23 +08:00
luochen570 d1be6d1f24 ci: use available Fedora mingw packages
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m44s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:51:54 +08:00
luochen570 1e34b10542 ci: avoid deleting checkout source during rsync
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 16s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:46:13 +08:00
luochen570 ae12b48973 ci: use latest Fedora image for cross build
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m10s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:42:29 +08:00
luochen570 4e530cb1dc ci: use supported Fedora image for cross build
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m34s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:30:23 +08:00
luochen570 9297fde7ea ci: disable Fedora OpenH264 repo in cross build
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 2s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:28:58 +08:00
luochen570 0ab0ea21c3 ci: use TUNA mirror for Fedora packages
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 2s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:27:57 +08:00
luochen570 4da3e64fcf ci: avoid remote actions in cross build
Cross Build Windows Release on Linux / cross-build-windows (push) Has been cancelled
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:12:49 +08:00
luochen570 f3fb7e877c ci: use 9950x runner for Linux cross build
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 31s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-29 23:46:42 +08:00
luochen570 f63480b5c2 ci: cross build Windows release on Linux
Cross Build Windows Release on Linux / cross-build-windows (push) Has been cancelled
Build Windows Release / build-windows (push) Has been cancelled
2026-05-29 23:41:51 +08:00
luochen570 6ff03ca32e ci: target self-hosted Windows runner
Build Windows Release / build-windows (push) Has been cancelled
2026-05-29 23:34:19 +08:00
luochen570 7df5312e16 chore: keep build tooling in workflow only
Build Windows Release / build-windows (push) Has been cancelled
2026-05-29 23:05:25 +08:00
luochen570 2a70d6245e ci: build Windows release package
Build Windows Release / build-windows (push) Has been cancelled
2026-05-29 22:59:55 +08:00
luochen570 8c9a92f2cb ci: build Linux release package
Build Linux Release / build-linux (push) Has been cancelled
2026-05-29 22:51:24 +08:00
luochen570 be4446c990 chore: use make for Linux binary dependency setup 2026-05-29 22:41:13 +08:00
luochen570 70a3e39397 Document Linux build toolchain versions 2026-05-29 22:31:49 +08:00
luochen570 81d586c032 Initial Linux Qt OpenCV project 2026-05-29 22:29:38 +08:00
12 changed files with 836 additions and 740 deletions
+202
View File
@@ -0,0 +1,202 @@
name: Build Windows Release
on:
push:
branches:
- main
tags:
- 'v*'
workflow_dispatch:
permissions:
contents: write
jobs:
build-windows-release:
name: Build Windows x64 Release
# Windows runner 已注册标签:windows-latest、windows-2022、self-hosted;均为 host 模式。
runs-on: windows-2022
env:
BUILD_TYPE: Release
MSYS2_ROOT: C:\msys64
MSYSTEM: UCRT64
CHERE_INVOKING: 1
PACKAGE_BASENAME: chengnan-windows-x64
PACKAGE_NAME: chengnan-windows-x64
steps:
- name: Prepare source
shell: powershell
run: |
$ErrorActionPreference = 'Stop'
$work = Join-Path $env:RUNNER_TEMP 'chengnan-src'
$srcFixed = Join-Path $env:RUNNER_TEMP 'chengnan-work'
$zip = Join-Path $env:RUNNER_TEMP 'chengnan-src.zip'
if (Test-Path $work) { Remove-Item -Recurse -Force $work }
if (Test-Path $srcFixed) { Remove-Item -Recurse -Force $srcFixed }
if (Test-Path $zip) { Remove-Item -Force $zip }
New-Item -ItemType Directory -Force -Path $work | Out-Null
$serverUrl = if ($env:GITHUB_SERVER_URL) { $env:GITHUB_SERVER_URL.TrimEnd('/') } else { 'https://git.luochen570.cn' }
$archiveUrl = "$serverUrl/$env:GITHUB_REPOSITORY/archive/$env:GITHUB_SHA.zip"
Write-Host "Downloading source archive from $archiveUrl"
Invoke-WebRequest -Uri $archiveUrl -OutFile $zip
Expand-Archive -Path $zip -DestinationPath $work -Force
$src = Get-ChildItem -Path $work -Directory | Select-Object -First 1
if (-not $src) { throw 'Source archive extraction produced no directory' }
Copy-Item -Path $src.FullName -Destination $srcFixed -Recurse -Force
Write-Host "Source dir: $srcFixed"
- name: Install MSYS2 and build dependencies
shell: powershell
run: |
$ErrorActionPreference = 'Stop'
$msysRoot = $env:MSYS2_ROOT
if (-not (Test-Path "$msysRoot\usr\bin\bash.exe")) {
$installer = Join-Path $env:RUNNER_TEMP 'msys2-installer.exe'
$installerUrl = 'https://github.com/msys2/msys2-installer/releases/latest/download/msys2-x86_64-latest.exe'
Write-Host "Downloading MSYS2 installer from $installerUrl"
Invoke-WebRequest -Uri $installerUrl -OutFile $installer
& $installer in --confirm-command --accept-messages --root $msysRoot
}
$bash = "$msysRoot\usr\bin\bash.exe"
& $bash -lc "pacman --noconfirm -Syuu"
if ($LASTEXITCODE -ne 0) { Write-Host 'First pacman system update returned non-zero; continuing with second update.' }
& $bash -lc "pacman --noconfirm -Syuu"
if ($LASTEXITCODE -ne 0) { throw "pacman system update failed, exit code: $LASTEXITCODE" }
& $bash -lc "pacman --noconfirm -S --needed git zip unzip p7zip mingw-w64-ucrt-x86_64-toolchain mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-ninja mingw-w64-ucrt-x86_64-qt6-base mingw-w64-ucrt-x86_64-qt6-imageformats"
if ($LASTEXITCODE -ne 0) { throw "pacman dependency installation failed, exit code: $LASTEXITCODE" }
- name: Configure and build
shell: powershell
run: |
$ErrorActionPreference = 'Stop'
$bash = "$env:MSYS2_ROOT\usr\bin\bash.exe"
$srcWin = Join-Path $env:RUNNER_TEMP 'chengnan-work'
$src = $srcWin -replace '\\','/'
$src = $src -replace '^([A-Za-z]):','/$1'
$src = $src.ToLower()
$script = @"
set -euo pipefail
cd '$src'
export PATH=/ucrt64/bin:/usr/bin:`$PATH
cmake -S . -B build-windows -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build-windows --parallel `$(nproc)
rm -rf dist-windows
mkdir -p dist-windows/chengnan
cp build-windows/chengnan.exe dist-windows/chengnan/
/ucrt64/bin/windeployqt6.exe --release --no-translations dist-windows/chengnan/chengnan.exe || /ucrt64/bin/windeployqt.exe --release --no-translations dist-windows/chengnan/chengnan.exe
printf '%s\n' 'chengnan Windows x64 package' '' 'Usage:' '1. Extract the whole directory.' '2. Double-click chengnan.exe to run.' '' 'Note:' '- This package is built by Windows Runner with MSYS2 UCRT64 + Qt.' '- Do not copy chengnan.exe alone; keep DLLs and Qt plugin directories together.' > dist-windows/chengnan/README.txt
"@
& $bash -lc $script
- name: Package
shell: powershell
run: |
$ErrorActionPreference = 'Stop'
$shortSha = $env:GITHUB_SHA.Substring(0, 10)
$version = if ($env:GITHUB_REF_TYPE -eq 'tag') { $env:GITHUB_REF_NAME } else { "build-$shortSha" }
$zipName = "$env:PACKAGE_BASENAME-$version.zip"
$sourceDir = Join-Path $env:RUNNER_TEMP 'chengnan-work'
$dist = Join-Path $sourceDir 'dist-windows\chengnan'
if (-not (Test-Path "$dist\chengnan.exe")) { throw "Missing build output: $dist\chengnan.exe" }
Push-Location (Split-Path $dist -Parent)
if (Test-Path (Join-Path $sourceDir $zipName)) { Remove-Item -Force (Join-Path $sourceDir $zipName) }
Compress-Archive -Path 'chengnan\*' -DestinationPath (Join-Path $sourceDir $zipName) -Force
Pop-Location
$zipPath = Join-Path $sourceDir $zipName
$hash = (Get-FileHash $zipPath -Algorithm SHA256).Hash.ToLowerInvariant()
"$hash $zipName" | Out-File -FilePath "$zipPath.sha256" -Encoding ascii
Write-Host "Package: $zipPath"
Write-Host "SHA256: $hash"
- name: Verify package
shell: powershell
run: |
$ErrorActionPreference = 'Stop'
$shortSha = $env:GITHUB_SHA.Substring(0, 10)
$version = if ($env:GITHUB_REF_TYPE -eq 'tag') { $env:GITHUB_REF_NAME } else { "build-$shortSha" }
$zipName = "$env:PACKAGE_BASENAME-$version.zip"
$sourceDir = Join-Path $env:RUNNER_TEMP 'chengnan-work'
$zipPath = Join-Path $sourceDir $zipName
$shaPath = "$zipPath.sha256"
if (-not (Test-Path $zipPath)) { throw "zip does not exist: $zipPath" }
if (-not (Test-Path $shaPath)) { throw "sha256 does not exist: $shaPath" }
if ((Get-Item $zipPath).Length -le 0) { throw "zip file is empty: $zipPath" }
Write-Host "Verified package: $zipPath"
- name: Upload package to repository release
shell: powershell
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
$ErrorActionPreference = 'Stop'
$token = $env:RELEASE_TOKEN
if ([string]::IsNullOrWhiteSpace($token)) { $token = $env:GITHUB_TOKEN }
if ([string]::IsNullOrWhiteSpace($token)) { throw 'Missing release token. Configure RELEASE_TOKEN in repository secrets or ensure GITHUB_TOKEN is available.' }
$shortSha = $env:GITHUB_SHA.Substring(0, 10)
$version = if ($env:GITHUB_REF_TYPE -eq 'tag') { $env:GITHUB_REF_NAME } else { "build-$shortSha" }
$zipName = "$env:PACKAGE_BASENAME-$version.zip"
$sourceDir = Join-Path $env:RUNNER_TEMP 'chengnan-work'
$zipPath = Join-Path $sourceDir $zipName
$shaPath = "$zipPath.sha256"
$serverUrl = if ($env:GITHUB_SERVER_URL) { $env:GITHUB_SERVER_URL.TrimEnd('/') } else { 'https://git.luochen570.cn' }
$repo = $env:GITHUB_REPOSITORY
$apiBase = "$serverUrl/api/v1/repos/$repo"
$tagName = $version
$releaseName = if ($env:GITHUB_REF_TYPE -eq 'tag') { $env:GITHUB_REF_NAME } else { "chengnan $shortSha" }
$isPrerelease = if ($env:GITHUB_REF_TYPE -eq 'tag') { $false } else { $true }
$headers = @{ Authorization = "token $token"; Accept = 'application/json' }
$releasePayload = @{
tag_name = $tagName
target_commitish = $env:GITHUB_SHA
name = $releaseName
body = "Automated Windows x64 build from Gitea Actions.`n"
draft = $false
prerelease = $isPrerelease
} | ConvertTo-Json -Depth 5
try {
$release = Invoke-RestMethod -Method Post -Uri "$apiBase/releases" -Headers $headers -ContentType 'application/json' -Body $releasePayload
} catch {
$release = Invoke-RestMethod -Method Get -Uri "$apiBase/releases/tags/$tagName" -Headers $headers
}
function Remove-ExistingAsset([string]$assetName) {
$assets = Invoke-RestMethod -Method Get -Uri "$apiBase/releases/$($release.id)/assets" -Headers $headers
foreach ($asset in @($assets)) {
if ($asset.name -eq $assetName) {
Invoke-RestMethod -Method Delete -Uri "$apiBase/releases/assets/$($asset.id)" -Headers $headers | Out-Null
}
}
}
function Upload-Asset([string]$path) {
$name = Split-Path $path -Leaf
Remove-ExistingAsset $name
$uploadUrl = "$apiBase/releases/$($release.id)/assets?name=$([uri]::EscapeDataString($name))"
$responseFile = Join-Path $env:RUNNER_TEMP "gitea-upload-response.json"
$curl = Join-Path $env:SystemRoot 'System32\curl.exe'
$status = & $curl --silent --show-error --location `
--header "Authorization: token $token" `
--form "attachment=@$path;filename=$name" `
--write-out '%{http_code}' `
--output $responseFile `
$uploadUrl
if ($status -ne '200' -and $status -ne '201') {
Write-Error "Upload release asset failed, HTTP ${status}: $name"
if (Test-Path $responseFile) { Get-Content $responseFile }
exit 1
}
Write-Host "Uploaded release asset: $name"
}
Upload-Asset $zipPath
Upload-Asset $shaPath
Write-Host "Release assets uploaded to $serverUrl/$repo/releases/tag/$tagName"
-14
View File
@@ -1,14 +0,0 @@
build/
build-windows/
build-wsl-windows/
cmake-build-*/
.qt/
.qtc/
CMakeUserPresets.json
*.user
*.suo
*.vcxproj*
*.sln
*.exe
*.dll
*.pdb
+31 -22
View File
@@ -1,30 +1,39 @@
cmake_minimum_required(VERSION 3.16)
project(QtOpenCVImageTool LANGUAGES CXX)
project(chengnan VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOUIC OFF)
set(CMAKE_AUTORCC OFF)
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)
find_package(OpenCV REQUIRED)
add_executable(QtOpenCVImageTool WIN32
main.cpp
MainWindow.h
MainWindow.cpp
)
target_link_libraries(QtOpenCVImageTool PRIVATE
Qt${QT_VERSION_MAJOR}::Widgets
${OpenCV_LIBS}
)
target_include_directories(QtOpenCVImageTool PRIVATE ${OpenCV_INCLUDE_DIRS})
if(QT_VERSION_MAJOR EQUAL 6)
qt_finalize_executable(QtOpenCVImageTool)
find_package(Qt6 QUIET COMPONENTS Widgets)
if (Qt6_FOUND)
qt_add_executable(chengnan
main.cpp
MainWindow.h
MainWindow.cpp
)
target_link_libraries(chengnan PRIVATE Qt6::Widgets)
else()
find_package(Qt5 REQUIRED COMPONENTS Widgets)
add_executable(chengnan
main.cpp
MainWindow.h
MainWindow.cpp
)
target_link_libraries(chengnan PRIVATE Qt5::Widgets)
endif()
target_compile_definitions(chengnan PRIVATE
CHENGNAN_APP_VERSION="${PROJECT_VERSION}"
)
if (MSVC)
target_compile_options(chengnan PRIVATE /W4 /permissive-)
else()
target_compile_options(chengnan PRIVATE -Wall -Wextra -Wpedantic)
endif()
install(TARGETS chengnan RUNTIME DESTINATION bin)
+311 -331
View File
@@ -1,433 +1,413 @@
#include "MainWindow.h"
#include <QCheckBox>
#include <QAction>
#include <QApplication>
#include <QFileDialog>
#include <QFileInfo>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QImage>
#include <QLabel>
#include <QImageReader>
#include <QImageWriter>
#include <QKeySequence>
#include <QMenuBar>
#include <QMessageBox>
#include <QPushButton>
#include <QPixmap>
#include <QScrollArea>
#include <QMouseEvent>
#include <QSlider>
#include <QStatusBar>
#include <QThread>
#include <QVBoxLayout>
#include <QToolBar>
#include <algorithm>
#include <cmath>
namespace
ImageLabel::ImageLabel(QWidget *parent)
: QLabel(parent)
{
QImage matToQImage(const cv::Mat &mat)
{
if (mat.empty()) {
return {};
}
cv::Mat rgb;
if (mat.channels() == 1) {
cv::cvtColor(mat, rgb, cv::COLOR_GRAY2RGB);
} else if (mat.channels() == 3) {
cv::cvtColor(mat, rgb, cv::COLOR_BGR2RGB);
} else if (mat.channels() == 4) {
cv::cvtColor(mat, rgb, cv::COLOR_BGRA2RGBA);
} else {
return {};
}
const QImage::Format format = rgb.channels() == 4 ? QImage::Format_RGBA8888 : QImage::Format_RGB888;
return QImage(rgb.data, rgb.cols, rgb.rows, static_cast<int>(rgb.step), format).copy();
setAlignment(Qt::AlignCenter);
setBackgroundRole(QPalette::Base);
setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
setScaledContents(false);
setMinimumSize(320, 240);
setText(tr("打开一张图片开始查看"));
}
cv::Mat rotateWithBounds(const cv::Mat &image, double angle)
void ImageLabel::mouseDoubleClickEvent(QMouseEvent *event)
{
if (image.empty() || std::abs(angle) < 0.01) {
return image.clone();
if (event->button() == Qt::LeftButton) {
Q_EMIT doubleClicked();
}
const cv::Point2f center(image.cols / 2.0F, image.rows / 2.0F);
cv::Mat matrix = cv::getRotationMatrix2D(center, angle, 1.0);
const cv::Rect2f bounds = cv::RotatedRect(cv::Point2f(), image.size(), angle).boundingRect2f();
matrix.at<double>(0, 2) += bounds.width / 2.0 - image.cols / 2.0;
matrix.at<double>(1, 2) += bounds.height / 2.0 - image.rows / 2.0;
cv::Mat rotated;
const cv::Size outputSize(static_cast<int>(bounds.width), static_cast<int>(bounds.height));
cv::warpAffine(image, rotated, matrix, outputSize, cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(30, 30, 30));
return rotated;
}
cv::Mat translateImage(const cv::Mat &image, int dx, int dy)
{
if (image.empty() || (dx == 0 && dy == 0)) {
return image.clone();
}
cv::Mat translated;
cv::Mat matrix = (cv::Mat_<double>(2, 3) << 1, 0, dx, 0, 1, dy);
cv::warpAffine(image, translated, matrix, image.size(), cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(30, 30, 30));
return translated;
}
cv::Mat extractTargets(const cv::Mat &image, int &targetCount)
{
targetCount = 0;
if (image.empty()) {
return {};
}
cv::Mat gray;
cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
cv::GaussianBlur(gray, gray, cv::Size(5, 5), 0);
cv::Mat binary;
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
if (cv::countNonZero(binary) > binary.rows * binary.cols / 2) {
cv::bitwise_not(binary, binary);
}
const cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 5));
cv::morphologyEx(binary, binary, cv::MORPH_OPEN, kernel);
cv::morphologyEx(binary, binary, cv::MORPH_CLOSE, kernel);
std::vector<std::vector<cv::Point>> contours;
cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
cv::Mat extracted = cv::Mat::zeros(image.size(), image.type());
image.copyTo(extracted, binary);
for (const auto &contour : contours) {
const double area = cv::contourArea(contour);
if (area < 300.0) {
continue;
}
++targetCount;
cv::rectangle(extracted, cv::boundingRect(contour), cv::Scalar(0, 255, 0), 2);
}
return extracted;
}
QString classifyImage(const cv::Mat &image, int targetCount)
{
if (image.empty()) {
return QStringLiteral("未载入图片");
}
cv::Scalar mean = cv::mean(image);
const double brightness = (mean[0] + mean[1] + mean[2]) / 3.0;
const QString light = brightness >= 170.0 ? QStringLiteral("偏亮")
: brightness <= 85.0 ? QStringLiteral("偏暗")
: QStringLiteral("亮度适中");
QString color = QStringLiteral("颜色均衡");
if (mean[2] > mean[1] + 18.0 && mean[2] > mean[0] + 18.0) {
color = QStringLiteral("红色占优");
} else if (mean[1] > mean[2] + 18.0 && mean[1] > mean[0] + 18.0) {
color = QStringLiteral("绿色占优");
} else if (mean[0] > mean[2] + 18.0 && mean[0] > mean[1] + 18.0) {
color = QStringLiteral("蓝色占优");
}
return QStringLiteral("分类结果:%1,%2;目标数量:%3").arg(light, color).arg(targetCount);
}
class ImageProcessorWorker : public QObject
{
Q_OBJECT
public slots:
void process(const cv::Mat &source, const ProcessParams &params)
{
if (source.empty()) {
emit processed(cv::Mat(), QStringLiteral("未载入图片"));
return;
}
cv::Mat output = source.clone();
if (std::abs(params.scale - 1.0) > 0.001) {
cv::resize(output, output, cv::Size(), params.scale, params.scale, cv::INTER_LINEAR);
}
output = translateImage(output, params.translateX, params.translateY);
output = rotateWithBounds(output, params.angle);
int targetCount = 0;
if (params.extractTarget) {
output = extractTargets(output, targetCount);
} else {
cv::Mat gray;
cv::cvtColor(output, gray, cv::COLOR_BGR2GRAY);
cv::Mat binary;
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
std::vector<std::vector<cv::Point>> contours;
cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
targetCount = static_cast<int>(std::count_if(contours.begin(), contours.end(), [](const auto &contour) {
return cv::contourArea(contour) >= 300.0;
}));
}
const QString classText = params.classifyImage ? classifyImage(output, targetCount) : QStringLiteral("处理完成");
emit processed(output, classText);
}
signals:
void processed(const cv::Mat &image, const QString &classText);
};
QLabel::mouseDoubleClickEvent(event);
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
qRegisterMetaType<cv::Mat>("cv::Mat");
qRegisterMetaType<ProcessParams>("ProcessParams");
createActions();
createMenus();
createToolbar();
createCentralWidget();
updateActions();
buildUi();
auto *worker = new ImageProcessorWorker;
workerThread = new QThread(this);
worker->moveToThread(workerThread);
connect(this, &MainWindow::processRequested, worker, &ImageProcessorWorker::process);
connect(worker, &ImageProcessorWorker::processed, this, &MainWindow::onProcessed);
connect(workerThread, &QThread::finished, worker, &QObject::deleteLater);
workerThread->start();
setWindowTitle(tr("chengnan 图片查看器"));
resize(1100, 720);
statusBar()->showMessage(tr("就绪"));
}
MainWindow::~MainWindow()
void MainWindow::createActions()
{
if (workerThread) {
workerThread->quit();
workerThread->wait();
}
openAction_ = new QAction(tr("打开(&O)"), this);
openAction_->setShortcut(QKeySequence::Open);
connect(openAction_, &QAction::triggered, this, &MainWindow::openImage);
saveAction_ = new QAction(tr("保存(&S)"), this);
saveAction_->setShortcut(QKeySequence::Save);
connect(saveAction_, &QAction::triggered, this, &MainWindow::saveImage);
saveAsAction_ = new QAction(tr("另存为(&A)"), this);
saveAsAction_->setShortcut(QKeySequence::SaveAs);
connect(saveAsAction_, &QAction::triggered, this, &MainWindow::saveImageAs);
exitAction_ = new QAction(tr("退出(&X)"), this);
exitAction_->setShortcut(QKeySequence::Quit);
connect(exitAction_, &QAction::triggered, this, &QWidget::close);
zoomInAction_ = new QAction(tr("放大"), this);
zoomInAction_->setShortcut(QKeySequence::ZoomIn);
connect(zoomInAction_, &QAction::triggered, this, &MainWindow::zoomIn);
zoomOutAction_ = new QAction(tr("缩小"), this);
zoomOutAction_->setShortcut(QKeySequence::ZoomOut);
connect(zoomOutAction_, &QAction::triggered, this, &MainWindow::zoomOut);
fitAction_ = new QAction(tr("适配窗口"), this);
fitAction_->setShortcut(Qt::CTRL | Qt::Key_F);
connect(fitAction_, &QAction::triggered, this, &MainWindow::fitToWindow);
resetAction_ = new QAction(tr("原始大小"), this);
resetAction_->setShortcut(Qt::CTRL | Qt::Key_0);
connect(resetAction_, &QAction::triggered, this, &MainWindow::resetView);
rotateLeftAction_ = new QAction(tr("左旋 90°"), this);
connect(rotateLeftAction_, &QAction::triggered, this, &MainWindow::rotateLeft);
rotateRightAction_ = new QAction(tr("右旋 90°"), this);
connect(rotateRightAction_, &QAction::triggered, this, &MainWindow::rotateRight);
flipHorizontalAction_ = new QAction(tr("水平翻转"), this);
connect(flipHorizontalAction_, &QAction::triggered, this, &MainWindow::flipHorizontal);
flipVerticalAction_ = new QAction(tr("垂直翻转"), this);
connect(flipVerticalAction_, &QAction::triggered, this, &MainWindow::flipVertical);
grayscaleAction_ = new QAction(tr("灰度化"), this);
connect(grayscaleAction_, &QAction::triggered, this, &MainWindow::grayscale);
invertAction_ = new QAction(tr("反色"), this);
connect(invertAction_, &QAction::triggered, this, &MainWindow::invertColors);
}
void MainWindow::buildUi()
void MainWindow::createMenus()
{
setWindowTitle(QStringLiteral("Qt + OpenCV 图像显示与处理"));
QMenu *fileMenu = menuBar()->addMenu(tr("文件(&F)"));
fileMenu->addAction(openAction_);
fileMenu->addAction(saveAction_);
fileMenu->addAction(saveAsAction_);
fileMenu->addSeparator();
fileMenu->addAction(exitAction_);
auto *central = new QWidget(this);
auto *rootLayout = new QVBoxLayout(central);
QMenu *viewMenu = menuBar()->addMenu(tr("查看(&V)"));
viewMenu->addAction(zoomInAction_);
viewMenu->addAction(zoomOutAction_);
viewMenu->addAction(fitAction_);
viewMenu->addAction(resetAction_);
auto *buttonLayout = new QHBoxLayout;
openButton = new QPushButton(QStringLiteral("打开图片"));
saveButton = new QPushButton(QStringLiteral("保存图片"));
saveAsButton = new QPushButton(QStringLiteral("另存图片"));
resetButton = new QPushButton(QStringLiteral("重置处理"));
buttonLayout->addWidget(openButton);
buttonLayout->addWidget(saveButton);
buttonLayout->addWidget(saveAsButton);
buttonLayout->addStretch();
buttonLayout->addWidget(resetButton);
QMenu *processMenu = menuBar()->addMenu(tr("处理(&P)"));
processMenu->addAction(rotateLeftAction_);
processMenu->addAction(rotateRightAction_);
processMenu->addAction(flipHorizontalAction_);
processMenu->addAction(flipVerticalAction_);
processMenu->addSeparator();
processMenu->addAction(grayscaleAction_);
processMenu->addAction(invertAction_);
}
auto *controlBox = new QGroupBox(QStringLiteral("图像处理"));
auto *controlLayout = new QHBoxLayout(controlBox);
void MainWindow::createToolbar()
{
QToolBar *toolbar = addToolBar(tr("主工具栏"));
toolbar->setMovable(false);
toolbar->addAction(openAction_);
toolbar->addAction(saveAction_);
toolbar->addSeparator();
toolbar->addAction(zoomOutAction_);
scaleSlider = new QSlider(Qt::Horizontal);
scaleSlider->setRange(25, 200);
scaleSlider->setValue(100);
rotateSlider = new QSlider(Qt::Horizontal);
rotateSlider->setRange(-180, 180);
translateXSlider = new QSlider(Qt::Horizontal);
translateXSlider->setRange(-200, 200);
translateYSlider = new QSlider(Qt::Horizontal);
translateYSlider->setRange(-200, 200);
extractCheckBox = new QCheckBox(QStringLiteral("目标提取"));
classifyCheckBox = new QCheckBox(QStringLiteral("图像分类"));
zoomSlider_ = new QSlider(Qt::Horizontal, this);
zoomSlider_->setRange(10, 400);
zoomSlider_->setValue(100);
zoomSlider_->setFixedWidth(180);
zoomSlider_->setToolTip(tr("缩放比例"));
connect(zoomSlider_, &QSlider::valueChanged, this, &MainWindow::updateZoomFromSlider);
toolbar->addWidget(zoomSlider_);
auto addSlider = [controlLayout](const QString &name, QSlider *slider) {
auto *box = new QWidget;
auto *layout = new QVBoxLayout(box);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(new QLabel(name));
layout->addWidget(slider);
controlLayout->addWidget(box, 1);
};
toolbar->addAction(zoomInAction_);
toolbar->addAction(fitAction_);
toolbar->addSeparator();
toolbar->addAction(rotateLeftAction_);
toolbar->addAction(rotateRightAction_);
toolbar->addAction(grayscaleAction_);
toolbar->addAction(invertAction_);
}
addSlider(QStringLiteral("缩放"), scaleSlider);
addSlider(QStringLiteral("旋转"), rotateSlider);
addSlider(QStringLiteral("水平平移"), translateXSlider);
addSlider(QStringLiteral("垂直平移"), translateYSlider);
controlLayout->addWidget(extractCheckBox);
controlLayout->addWidget(classifyCheckBox);
void MainWindow::createCentralWidget()
{
imageLabel_ = new ImageLabel(this);
connect(imageLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow);
auto *imageLayout = new QHBoxLayout;
originalLabel = new QLabel(QStringLiteral("原图"));
resultLabel = new QLabel(QStringLiteral("处理后图像"));
originalLabel->setAlignment(Qt::AlignCenter);
resultLabel->setAlignment(Qt::AlignCenter);
originalLabel->setMinimumSize(480, 420);
resultLabel->setMinimumSize(480, 420);
originalLabel->setStyleSheet("QLabel { background:#202124; color:white; border:1px solid #555; }");
resultLabel->setStyleSheet("QLabel { background:#202124; color:white; border:1px solid #555; }");
auto *originalScroll = new QScrollArea;
auto *resultScroll = new QScrollArea;
originalScroll->setWidget(originalLabel);
resultScroll->setWidget(resultLabel);
originalScroll->setWidgetResizable(true);
resultScroll->setWidgetResizable(true);
imageLayout->addWidget(originalScroll, 1);
imageLayout->addWidget(resultScroll, 1);
rootLayout->addLayout(buttonLayout);
rootLayout->addWidget(controlBox);
rootLayout->addLayout(imageLayout, 1);
setCentralWidget(central);
statusLabel = new QLabel(QStringLiteral("请打开一张图片"));
statusBar()->addWidget(statusLabel, 1);
connect(openButton, &QPushButton::clicked, this, &MainWindow::openImage);
connect(saveButton, &QPushButton::clicked, this, &MainWindow::saveImage);
connect(saveAsButton, &QPushButton::clicked, this, &MainWindow::saveImageAs);
connect(resetButton, &QPushButton::clicked, this, &MainWindow::resetParams);
connect(scaleSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
connect(rotateSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
connect(translateXSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
connect(translateYSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
connect(extractCheckBox, &QCheckBox::toggled, this, &MainWindow::scheduleProcessing);
connect(classifyCheckBox, &QCheckBox::toggled, this, &MainWindow::scheduleProcessing);
scrollArea_ = new QScrollArea(this);
scrollArea_->setBackgroundRole(QPalette::Dark);
scrollArea_->setWidget(imageLabel_);
scrollArea_->setWidgetResizable(true);
setCentralWidget(scrollArea_);
}
void MainWindow::openImage()
{
const QString fileName = QFileDialog::getOpenFileName(
this,
QStringLiteral("打开图片"),
tr("打开图片"),
QString(),
QStringLiteral("Images (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)"));
tr("图片文件 (*.png *.jpg *.jpeg *.bmp *.gif *.webp);;所有文件 (*.*)"));
if (fileName.isEmpty()) {
return;
}
originalImage = cv::imread(fileName.toLocal8Bit().constData(), cv::IMREAD_COLOR);
if (originalImage.empty()) {
QMessageBox::warning(this, QStringLiteral("打开失败"), QStringLiteral("无法读取该图片文件。"));
QImageReader reader(fileName);
reader.setAutoTransform(true);
const QImage image = reader.read();
if (image.isNull()) {
QMessageBox::warning(this, tr("打开失败"), tr("无法读取图片:%1").arg(reader.errorString()));
return;
}
savePath.clear();
updateOriginalView();
scheduleProcessing();
statusLabel->setText(QStringLiteral("已打开:%1").arg(QFileInfo(fileName).fileName()));
setImage(image, fileName);
}
void MainWindow::saveImage()
{
if (savePath.isEmpty()) {
if (!ensureImageLoaded(tr("保存"))) {
return;
}
if (currentPath_.isEmpty()) {
saveImageAs();
return;
}
if (writeResultToFile(savePath)) {
statusLabel->setText(QStringLiteral("已保存:%1").arg(QFileInfo(savePath).fileName()));
}
writeImageToPath(currentPath_);
}
void MainWindow::saveImageAs()
{
if (resultImage.empty()) {
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("请先打开并处理图片。"));
if (!ensureImageLoaded(tr("另存为"))) {
return;
}
const QString fileName = QFileDialog::getSaveFileName(
this,
QStringLiteral("另存图片"),
QStringLiteral("processed.png"),
QStringLiteral("PNG (*.png);;JPEG (*.jpg *.jpeg);;BMP (*.bmp);;TIFF (*.tif *.tiff)"));
tr("另存为"),
currentPath_.isEmpty() ? QStringLiteral("chengnan.png") : currentPath_,
tr("PNG 图片 (*.png);;JPEG 图片 (*.jpg *.jpeg);;BMP 图片 (*.bmp);;所有文件 (*.*)"));
if (fileName.isEmpty()) {
if (!fileName.isEmpty()) {
writeImageToPath(fileName);
}
}
void MainWindow::zoomIn()
{
setZoomFactor(zoomFactor_ * 1.25);
}
void MainWindow::zoomOut()
{
setZoomFactor(zoomFactor_ / 1.25);
}
void MainWindow::fitToWindow()
{
if (!ensureImageLoaded(tr("适配窗口"))) {
return;
}
if (writeResultToFile(fileName)) {
savePath = fileName;
statusLabel->setText(QStringLiteral("已另存为:%1").arg(QFileInfo(fileName).fileName()));
}
}
void MainWindow::resetParams()
{
scaleSlider->setValue(100);
rotateSlider->setValue(0);
translateXSlider->setValue(0);
translateYSlider->setValue(0);
extractCheckBox->setChecked(false);
classifyCheckBox->setChecked(false);
scheduleProcessing();
}
void MainWindow::scheduleProcessing()
{
if (originalImage.empty()) {
const QSize viewportSize = scrollArea_->viewport()->size();
const QSize imageSize = currentImage_.size();
if (imageSize.isEmpty()) {
return;
}
emit processRequested(originalImage.clone(), currentParams());
const double xRatio = static_cast<double>(viewportSize.width()) / imageSize.width();
const double yRatio = static_cast<double>(viewportSize.height()) / imageSize.height();
setZoomFactor(std::min(xRatio, yRatio));
}
void MainWindow::onProcessed(const cv::Mat &image, const QString &classText)
void MainWindow::resetView()
{
resultImage = image.clone();
updateResultView();
statusLabel->setText(classText);
setZoomFactor(1.0);
}
void MainWindow::updateOriginalView()
void MainWindow::rotateLeft()
{
setImageOnLabel(originalLabel, originalImage);
if (!ensureImageLoaded(tr("旋转"))) {
return;
}
QTransform transform;
transform.rotate(-90);
applyTransformedImage(currentImage_.transformed(transform, Qt::SmoothTransformation));
}
void MainWindow::updateResultView()
void MainWindow::rotateRight()
{
setImageOnLabel(resultLabel, resultImage);
if (!ensureImageLoaded(tr("旋转"))) {
return;
}
QTransform transform;
transform.rotate(90);
applyTransformedImage(currentImage_.transformed(transform, Qt::SmoothTransformation));
}
void MainWindow::setImageOnLabel(QLabel *label, const cv::Mat &mat)
void MainWindow::flipHorizontal()
{
const QImage image = matToQImage(mat);
if (image.isNull()) {
label->setText(QStringLiteral("无图像"));
if (!ensureImageLoaded(tr("翻转"))) {
return;
}
applyTransformedImage(currentImage_.mirrored(true, false));
}
void MainWindow::flipVertical()
{
if (!ensureImageLoaded(tr("翻转"))) {
return;
}
applyTransformedImage(currentImage_.mirrored(false, true));
}
void MainWindow::grayscale()
{
if (!ensureImageLoaded(tr("灰度化"))) {
return;
}
applyTransformedImage(currentImage_.convertToFormat(QImage::Format_Grayscale8));
}
void MainWindow::invertColors()
{
if (!ensureImageLoaded(tr("反色"))) {
return;
}
QImage image = currentImage_.convertToFormat(QImage::Format_ARGB32);
image.invertPixels(QImage::InvertRgb);
applyTransformedImage(image);
}
void MainWindow::updateZoomFromSlider(int value)
{
const double factor = static_cast<double>(value) / 100.0;
if (std::abs(factor - zoomFactor_) > 0.001) {
zoomFactor_ = factor;
updateImageView();
}
}
void MainWindow::setImage(const QImage &image, const QString &path)
{
currentImage_ = image.convertToFormat(QImage::Format_ARGB32);
currentPath_ = path;
setZoomFactor(1.0);
updateActions();
const QFileInfo info(path);
setWindowTitle(path.isEmpty()
? tr("chengnan 图片查看器")
: tr("%1 - chengnan 图片查看器").arg(info.fileName()));
statusBar()->showMessage(tr("已加载:%1 × %2").arg(currentImage_.width()).arg(currentImage_.height()), 5000);
}
void MainWindow::updateImageView()
{
if (currentImage_.isNull()) {
imageLabel_->setPixmap(QPixmap());
imageLabel_->setText(tr("打开一张图片开始查看"));
return;
}
label->setPixmap(QPixmap::fromImage(image).scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
const QSize scaledSize = currentImage_.size() * zoomFactor_;
const QPixmap pixmap = QPixmap::fromImage(currentImage_).scaled(
scaledSize,
Qt::KeepAspectRatio,
Qt::SmoothTransformation);
imageLabel_->setText(QString());
imageLabel_->setPixmap(pixmap);
imageLabel_->resize(pixmap.size());
if (zoomSlider_->value() != static_cast<int>(zoomFactor_ * 100.0)) {
zoomSlider_->blockSignals(true);
zoomSlider_->setValue(static_cast<int>(zoomFactor_ * 100.0));
zoomSlider_->blockSignals(false);
}
statusBar()->showMessage(tr("缩放:%1%").arg(static_cast<int>(zoomFactor_ * 100.0)));
}
ProcessParams MainWindow::currentParams() const
void MainWindow::setZoomFactor(double factor)
{
ProcessParams params;
params.scale = scaleSlider->value() / 100.0;
params.angle = rotateSlider->value();
params.translateX = translateXSlider->value();
params.translateY = translateYSlider->value();
params.extractTarget = extractCheckBox->isChecked();
params.classifyImage = classifyCheckBox->isChecked();
return params;
zoomFactor_ = std::clamp(factor, 0.10, 4.00);
updateImageView();
}
bool MainWindow::writeResultToFile(const QString &fileName)
void MainWindow::applyTransformedImage(const QImage &image)
{
if (resultImage.empty()) {
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("没有可保存的处理结果。"));
return false;
currentImage_ = image.convertToFormat(QImage::Format_ARGB32);
updateImageView();
updateActions();
statusBar()->showMessage(tr("处理完成,可保存结果"), 3000);
}
void MainWindow::updateActions()
{
const bool hasImage = !currentImage_.isNull();
saveAction_->setEnabled(hasImage);
saveAsAction_->setEnabled(hasImage);
zoomInAction_->setEnabled(hasImage);
zoomOutAction_->setEnabled(hasImage);
fitAction_->setEnabled(hasImage);
resetAction_->setEnabled(hasImage);
rotateLeftAction_->setEnabled(hasImage);
rotateRightAction_->setEnabled(hasImage);
flipHorizontalAction_->setEnabled(hasImage);
flipVerticalAction_->setEnabled(hasImage);
grayscaleAction_->setEnabled(hasImage);
invertAction_->setEnabled(hasImage);
zoomSlider_->setEnabled(hasImage);
}
bool MainWindow::ensureImageLoaded(const QString &actionName) const
{
if (!currentImage_.isNull()) {
return true;
}
if (!cv::imwrite(fileName.toLocal8Bit().constData(), resultImage)) {
QMessageBox::warning(this, QStringLiteral("保存失败"), QStringLiteral("无法写入该图片文件。"));
QMessageBox::information(nullptr, actionName, tr("请先打开一张图片。"));
return false;
}
bool MainWindow::writeImageToPath(const QString &path)
{
QImageWriter writer(path);
if (!writer.write(currentImage_)) {
QMessageBox::warning(this, tr("保存失败"), tr("无法保存图片:%1").arg(writer.errorString()));
return false;
}
currentPath_ = path;
setWindowTitle(tr("%1 - chengnan 图片查看器").arg(QFileInfo(path).fileName()));
statusBar()->showMessage(tr("已保存:%1").arg(path), 5000);
return true;
}
#include "MainWindow.moc"
+63 -49
View File
@@ -1,76 +1,90 @@
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QImage>
#include <QLabel>
#include <QMainWindow>
#include <QMetaType>
#include <QPixmap>
#include <QScrollArea>
#include <QString>
#include <opencv2/opencv.hpp>
class QLabel;
class QAction;
class QMenu;
class QPushButton;
class QSlider;
class QCheckBox;
class QThread;
struct ProcessParams
class ImageLabel final : public QLabel
{
double scale = 1.0;
int translateX = 0;
int translateY = 0;
double angle = 0.0;
bool extractTarget = false;
bool classifyImage = false;
Q_OBJECT
public:
explicit ImageLabel(QWidget *parent = nullptr);
Q_SIGNALS:
void doubleClicked();
protected:
void mouseDoubleClickEvent(QMouseEvent *event) override;
};
Q_DECLARE_METATYPE(cv::Mat)
Q_DECLARE_METATYPE(ProcessParams)
class MainWindow : public QMainWindow
class MainWindow final : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow() override;
signals:
void processRequested(const cv::Mat &image, const ProcessParams &params);
private slots:
private Q_SLOTS:
void openImage();
void saveImage();
void saveImageAs();
void resetParams();
void scheduleProcessing();
void onProcessed(const cv::Mat &image, const QString &classText);
void zoomIn();
void zoomOut();
void fitToWindow();
void resetView();
void rotateLeft();
void rotateRight();
void flipHorizontal();
void flipVertical();
void grayscale();
void invertColors();
void updateZoomFromSlider(int value);
private:
void buildUi();
void updateOriginalView();
void updateResultView();
void setImageOnLabel(QLabel *label, const cv::Mat &mat);
ProcessParams currentParams() const;
bool writeResultToFile(const QString &fileName);
void createActions();
void createMenus();
void createToolbar();
void createCentralWidget();
void setImage(const QImage &image, const QString &path = QString());
void updateImageView();
void setZoomFactor(double factor);
void applyTransformedImage(const QImage &image);
void updateActions();
bool ensureImageLoaded(const QString &actionName) const;
bool writeImageToPath(const QString &path);
QLabel *originalLabel = nullptr;
QLabel *resultLabel = nullptr;
QLabel *statusLabel = nullptr;
QPushButton *openButton = nullptr;
QPushButton *saveButton = nullptr;
QPushButton *saveAsButton = nullptr;
QPushButton *resetButton = nullptr;
QSlider *scaleSlider = nullptr;
QSlider *rotateSlider = nullptr;
QSlider *translateXSlider = nullptr;
QSlider *translateYSlider = nullptr;
QCheckBox *extractCheckBox = nullptr;
QCheckBox *classifyCheckBox = nullptr;
ImageLabel *imageLabel_ = nullptr;
QScrollArea *scrollArea_ = nullptr;
QSlider *zoomSlider_ = nullptr;
cv::Mat originalImage;
cv::Mat resultImage;
QString savePath;
QImage currentImage_;
QString currentPath_;
double zoomFactor_ = 1.0;
QThread *workerThread = nullptr;
QAction *openAction_ = nullptr;
QAction *saveAction_ = nullptr;
QAction *saveAsAction_ = nullptr;
QAction *exitAction_ = nullptr;
QAction *zoomInAction_ = nullptr;
QAction *zoomOutAction_ = nullptr;
QAction *fitAction_ = nullptr;
QAction *resetAction_ = nullptr;
QAction *rotateLeftAction_ = nullptr;
QAction *rotateRightAction_ = nullptr;
QAction *flipHorizontalAction_ = nullptr;
QAction *flipVerticalAction_ = nullptr;
QAction *grayscaleAction_ = nullptr;
QAction *invertAction_ = nullptr;
};
#endif
#endif // MAINWINDOW_H
Binary file not shown.
+100
View File
@@ -0,0 +1,100 @@
param(
[Parameter(Mandatory = $true)]
[string]$QtPrefix,
[string]$BuildDir = "build-windows",
[string]$DistDir = "dist-windows\chengnan",
[string]$Generator = "Visual Studio 17 2022",
[string]$Arch = "x64",
[ValidateSet("Debug", "Release", "RelWithDebInfo", "MinSizeRel")]
[string]$Config = "Release"
)
$ErrorActionPreference = "Stop"
function Resolve-FullPath([string]$PathValue) {
if ([System.IO.Path]::IsPathRooted($PathValue)) {
return [System.IO.Path]::GetFullPath($PathValue)
}
return [System.IO.Path]::GetFullPath((Join-Path (Get-Location) $PathValue))
}
function Require-Command([string]$Name) {
$command = Get-Command $Name -ErrorAction SilentlyContinue
if (-not $command) {
throw "找不到命令:$Name。请先安装并加入 PATH。"
}
return $command.Source
}
$ProjectDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $ProjectDir
$QtPrefix = Resolve-FullPath $QtPrefix
$BuildPath = Resolve-FullPath $BuildDir
$DistPath = Resolve-FullPath $DistDir
$QtBin = Join-Path $QtPrefix "bin"
$WinDeployQt = Join-Path $QtBin "windeployqt.exe"
if (-not (Test-Path $QtPrefix)) {
throw "QtPrefix 不存在:$QtPrefix"
}
if (-not (Test-Path $WinDeployQt)) {
throw "找不到 windeployqt:$WinDeployQt。请确认 -QtPrefix 指向 Qt 套件目录,例如 C:\Qt\6.7.2\msvc2019_64。"
}
Require-Command "cmake" | Out-Null
$env:PATH = "$QtBin;$env:PATH"
$env:CMAKE_PREFIX_PATH = $QtPrefix
Write-Host "== chengnan Windows 构建 ==" -ForegroundColor Cyan
Write-Host "项目目录:$ProjectDir"
Write-Host "Qt 目录:$QtPrefix"
Write-Host "构建目录:$BuildPath"
Write-Host "发布目录:$DistPath"
Write-Host "生成器:$Generator"
Write-Host "配置:$Config"
$configureArgs = @(
"-S", $ProjectDir,
"-B", $BuildPath,
"-G", $Generator,
"-DCMAKE_PREFIX_PATH=$QtPrefix"
)
if ($Generator -like "Visual Studio*") {
$configureArgs += @("-A", $Arch)
} else {
$configureArgs += "-DCMAKE_BUILD_TYPE=$Config"
}
Write-Host "`n== 配置 CMake ==" -ForegroundColor Cyan
& cmake @configureArgs
Write-Host "`n== 编译 ==" -ForegroundColor Cyan
& cmake --build $BuildPath --config $Config --parallel
$ExeCandidates = @(
(Join-Path $BuildPath "$Config\chengnan.exe"),
(Join-Path $BuildPath "chengnan.exe")
)
$ExePath = $ExeCandidates | Where-Object { Test-Path $_ } | Select-Object -First 1
if (-not $ExePath) {
throw "构建完成但找不到 chengnan.exe。已检查:$($ExeCandidates -join ', ')"
}
Write-Host "`n== 准备发布目录 ==" -ForegroundColor Cyan
if (Test-Path $DistPath) {
Remove-Item -Recurse -Force $DistPath
}
New-Item -ItemType Directory -Force -Path $DistPath | Out-Null
Copy-Item $ExePath $DistPath
Write-Host "`n== 收集 Qt 运行库 ==" -ForegroundColor Cyan
$DistExe = Join-Path $DistPath "chengnan.exe"
& $WinDeployQt --release --no-translations $DistExe
Write-Host "`n构建完成:$DistExe" -ForegroundColor Green
Write-Host "请整体复制目录:$DistPath"
-46
View File
@@ -1,46 +0,0 @@
@echo off
setlocal
rem Usage:
rem build_windows.bat C:\Qt\6.6.0\msvc2019_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
rem build_windows.bat C:\Qt\6.6.0\mingw_64 C:\opencv-mingw\install "MinGW Makefiles"
if "%~1"=="" (
echo Usage: %~nx0 ^<QtDir^> ^<OpenCV_DIR^> [CMakeGenerator]
echo Example MSVC : %~nx0 C:\Qt\6.6.0\msvc2019_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
echo Example MinGW: %~nx0 C:\Qt\6.6.0\mingw_64 C:\opencv-mingw\install "MinGW Makefiles"
exit /b 1
)
if "%~2"=="" (
echo Missing OpenCV_DIR.
exit /b 1
)
set QT_DIR=%~1
set OPENCV_DIR=%~2
set GENERATOR=%~3
if "%GENERATOR%"=="" (
set GENERATOR=Visual Studio 17 2022
)
if not exist build-windows (
mkdir build-windows
)
if /I "%GENERATOR%"=="MinGW Makefiles" (
cmake -S . -B build-windows -G "%GENERATOR%" -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="%QT_DIR%" -DOpenCV_DIR="%OPENCV_DIR%"
) else (
cmake -S . -B build-windows -G "%GENERATOR%" -A x64 -DCMAKE_PREFIX_PATH="%QT_DIR%" -DOpenCV_DIR="%OPENCV_DIR%"
)
if errorlevel 1 exit /b %errorlevel%
cmake --build build-windows --config Release
if errorlevel 1 exit /b %errorlevel%
echo.
echo Build finished.
echo For MSVC, check: build-windows\Release\QtOpenCVImageTool.exe
echo For MinGW, check: build-windows\QtOpenCVImageTool.exe
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
if ! command -v x86_64-w64-mingw32-g++ >/dev/null 2>&1; then
echo "Missing x86_64-w64-mingw32-g++."
echo "Install it in WSL with: sudo apt install mingw-w64"
exit 1
fi
if [[ "${QT_MINGW_PREFIX:-}" == "" ]]; then
echo "Missing QT_MINGW_PREFIX."
echo "Example: export QT_MINGW_PREFIX=/opt/mxe/usr/x86_64-w64-mingw32.shared/qt6"
exit 1
fi
if [[ "${OpenCV_DIR:-}" == "" ]]; then
echo "Missing OpenCV_DIR."
echo "Example: export OpenCV_DIR=/opt/mxe/usr/x86_64-w64-mingw32.shared/lib/cmake/opencv4"
exit 1
fi
cmake -S . -B build-wsl-windows \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw64.cmake \
-DCMAKE_PREFIX_PATH="${QT_MINGW_PREFIX}" \
-DOpenCV_DIR="${OpenCV_DIR}"
cmake --build build-wsl-windows --config Release
echo "Windows executable should be under build-wsl-windows/."
-11
View File
@@ -1,11 +0,0 @@
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_PROCESSOR x86_64)
set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++)
set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
+4 -2
View File
@@ -5,10 +5,12 @@
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QApplication::setApplicationName(QStringLiteral("chengnan"));
QApplication::setApplicationVersion(QStringLiteral(CHENGNAN_APP_VERSION));
QApplication::setOrganizationName(QStringLiteral("luochen570"));
MainWindow window;
window.resize(1180, 760);
window.show();
return app.exec();
return QApplication::exec();
}
+125 -235
View File
@@ -1,259 +1,149 @@
# Qt + OpenCV 图像显示与处理
# chengnan
本工程使用 Qt Widgets 设计界面,使用 OpenCV 完成图像处理。程序支持打开图片、保存图片、另存图片,支持缩放、平移、旋转,并提供目标提取和简单图像分类功能。图像显示使用 Qt 的 `QLabel`/`QWidget`,没有使用 `cv::imshow`。
项目链接:<https://git.luochen570.cn/luochen570/chengnan>
## 文件说明
- `CMakeLists.txt`:CMake 工程配置。
- `main.cpp`:程序入口。
- `MainWindow.h`:主窗口类和处理参数声明。
- `MainWindow.cpp`:界面、图像读写、Qt 线程和 OpenCV 处理实现。
`chengnan` 是一个轻量级 Windows 图片查看器 / 简单图片处理工具,使用 **Qt Widgets + CMake + C++17** 开发。
## 功能
- 打开图片:读取 `png/jpg/bmp/tif` 等常见格式。
- 保存图片:保存当前处理结果。
- 另存图片:将处理结果保存为新文件。
- 显示对比:左侧显示处理前图像,右侧显示处理后图像。
- 基本处理:缩放、水平平移、垂直平移、旋转。
- 目标提取:使用灰度化、Otsu 阈值、形态学处理和轮廓检测提取前景目标,并用绿色矩形框标记目标。
- 图像分类:根据平均亮度和主色通道给出简单分类,同时显示目标数量。
- 线程处理:图像处理工作对象运行在 `QThread` 中,避免阻塞界面。
当前实现:
## Windows 构建说明
- 打开图片:PNG、JPG、JPEG、BMP、GIF、WebP 等 Qt 支持的格式
- 保存当前图片
- 另存为 PNG / JPG / BMP 等格式
- 图片显示:使用 Qt Widgets,不使用 OpenCV 窗口
- 缩放:工具栏滑块、放大、缩小、原始大小
- 双击图片适配窗口
- 旋转:左旋 90°、右旋 90°
- 翻转:水平翻转、垂直翻转
- 简单处理:灰度化、反色
本工程使用 CMake 管理,目标是构建 Windows 桌面应用程序 `QtOpenCVImageTool.exe`。推荐使用 **MSVC 64 位**,因为 OpenCV 官方 Windows 预编译包通常就是 MSVC 版本,配置最省事。
构建时请保持三者一致:
- 编译器一致:MSVC 对 MSVC,MinGW 对 MinGW。
- 位数一致:建议全部使用 64 位。
- Qt、OpenCV、CMake 使用同一套构建环境。
如果使用 MSVC,则不要混用 MinGW 版 Qt;如果使用 MinGW,则不要直接使用 OpenCV 官方 MSVC 预编译包。
### 需要安装的软件
1. Visual Studio 2022 或 Visual Studio 2022 Build Tools
安装时勾选:
## 文件结构
```text
Desktop development with C++
MSVC v143 x64/x86 build tools
Windows 10 SDK 或 Windows 11 SDK
C++ CMake tools for Windows
chengnan/
├── CMakeLists.txt
├── MainWindow.cpp
├── MainWindow.h
├── build-windows.ps1
├── main.cpp
└── readme.md
```
安装完成后,系统中应能找到类似路径:
## Windows 编译需要的工具
推荐环境:Windows 10 / Windows 11 x64。
必须安装:
1. **Git for Windows**
- 下载:<https://git-scm.com/download/win>
- 用于克隆项目源码。
2. **CMake 3.16 或更高版本**
- 下载:<https://cmake.org/download/>
- 安装时建议勾选 `Add CMake to the system PATH`。
3. **Qt 6 或 Qt 5,包含 Widgets 模块**
- 下载:<https://www.qt.io/download-qt-installer-oss>
- 推荐安装 Qt 6.x 的 MSVC 64-bit 套件,例如 `msvc2019_64` 或 `msvc2022_64`。
- 项目不依赖 OpenCV。
4. **Visual Studio 2022 Build Tools 或 Visual Studio 2022**
- 下载:<https://visualstudio.microsoft.com/zh-hans/downloads/>
- 需要安装组件:`使用 C++ 的桌面开发`。
- 提供 MSVC 编译器和 Windows SDK。
可选工具:
- **Ninja**:<https://github.com/ninja-build/ninja/releases>
- 如果使用 Ninja,可以把 `build-windows.ps1` 的 `-Generator` 参数改成 `Ninja`。
## 获取源码
```powershell
git clone https://git.luochen570.cn/luochen570/chengnan.git
cd chengnan
```
如果仓库主分支已切换到当前版本,直接构建即可;否则可手动切换:
```powershell
git checkout main
```
## 一键构建(推荐)
在 Windows PowerShell 中进入项目目录,然后执行:
```powershell
powershell -ExecutionPolicy Bypass -File .\build-windows.ps1 -QtPrefix "C:\Qt\6.7.2\msvc2019_64"
```
请把 `-QtPrefix` 改成你本机实际 Qt 安装目录。例如:
```powershell
powershell -ExecutionPolicy Bypass -File .\build-windows.ps1 -QtPrefix "C:\Qt\6.8.0\msvc2022_64"
```
脚本会完成:
1. 检查 Qt、CMake、编译器环境
2. 生成 CMake 构建目录
3. 编译 Release 版本
4. 调用 `windeployqt` 收集 Qt 运行库
5. 把发布文件放到 `dist-windows\chengnan`
构建成功后,运行:
```powershell
.\dist-windows\chengnan\chengnan.exe
```
## 手动构建
如果不使用脚本,也可以手动执行:
```powershell
cmake -S . -B build-windows -G "Visual Studio 17 2022" -A x64 -DCMAKE_PREFIX_PATH="C:\Qt\6.7.2\msvc2019_64"
cmake --build build-windows --config Release
```
打包 Qt 运行库:
```powershell
C:\Qt\6.7.2\msvc2019_64\bin\windeployqt.exe --release --no-translations build-windows\Release\chengnan.exe
```
## 常见问题
### 找不到 Qt
确认 `-QtPrefix` 指向 Qt 套件目录,而不是 Qt 根目录。例如应使用:
```text
C:\Program Files\Microsoft Visual Studio\2022\Community
C:\Program Files\Microsoft Visual Studio\2022\BuildTools
C:\Qt\6.7.2\msvc2019_64
```
2. Qt for Windows
使用 Qt Online Installer 安装 Qt。推荐安装 Qt 6.x,并勾选 MSVC 64 位组件,例如:
不要写成:
```text
Qt 6.6.x
MSVC 2019 64-bit 或 MSVC 2022 64-bit
Qt Creator
C:\Qt
```
安装完成后,Qt 路径通常类似:
### 找不到 MSVC 编译器
```text
C:\Qt\6.6.0\msvc2019_64
C:\Qt\6.6.0\msvc2022_64
```
请安装 Visual Studio 2022 的 `使用 C++ 的桌面开发`,然后在 “x64 Native Tools Command Prompt for VS 2022” 或已配置 VS 环境的 PowerShell 里运行构建脚本。
该目录下应存在:
### exe 复制到其它电脑无法运行
```text
C:\Qt\6.6.0\msvc2019_64\lib\cmake\Qt6\Qt6Config.cmake
```
请运行 `build-windows.ps1`,并整体复制 `dist-windows\chengnan` 文件夹,不要只复制单个 `chengnan.exe`。
3. OpenCV for Windows
## 开发说明
可以使用 OpenCV 官方 Windows 包。解压或安装到例如:
```text
C:\opencv
```
常见的 CMake 配置路径是:
```text
C:\opencv\build\x64\vc16\lib
```
该目录下应存在:
```text
C:\opencv\build\x64\vc16\lib\OpenCVConfig.cmake
```
4. CMake
如果安装 Visual Studio 时勾选了 CMake 工具,通常已经够用。也可以单独安装 CMake for Windows。命令行检查:
```bat
cmake --version
```
### 推荐方式:Qt Creator 构建
1. 打开 Qt Creator。
2. 选择“打开项目”,打开本目录的 `CMakeLists.txt`。
3. 选择 Windows Kit,例如:
```text
Desktop Qt 6.x.x MSVC 2019 64-bit
Desktop Qt 6.x.x MSVC 2022 64-bit
```
4. 如果 CMake 找不到 OpenCV,在 Qt Creator 的 CMake 配置项中添加:
```text
OpenCV_DIR=C:/opencv/build/x64/vc16/lib
```
5. 配置完成后点击“构建”。
6. 构建成功后会生成 `QtOpenCVImageTool.exe`。
7. 在 Qt Creator 中点击“运行”即可启动程序。
### 命令行构建:MSVC
打开开始菜单中的:
```text
x64 Native Tools Command Prompt for VS 2022
```
进入工程目录,例如:
```bat
cd /d D:\QtOpenCVImageTool
```
使用项目提供的脚本构建:
```bat
build_windows.bat C:\Qt\6.6.0\msvc2019_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
```
如果你的 Qt 是 MSVC 2022 版本,路径可改为:
```bat
build_windows.bat C:\Qt\6.6.0\msvc2022_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
```
也可以手动执行 CMake:
```bat
mkdir build-windows
cd build-windows
cmake .. -G "Visual Studio 17 2022" -A x64 -DCMAKE_PREFIX_PATH=C:\Qt\6.6.0\msvc2019_64 -DOpenCV_DIR=C:\opencv\build\x64\vc16\lib
cmake --build . --config Release
```
MSVC 生成的 exe 通常位于:
```text
build-windows\Release\QtOpenCVImageTool.exe
```
### 命令行构建:MinGW
如果使用 MinGW,需要安装 MinGW 版 Qt,并准备 MinGW 编译出来的 OpenCV。不要把 MSVC 版 OpenCV 直接给 MinGW 使用。
示例:
```bat
build_windows.bat C:\Qt\6.6.0\mingw_64 C:\opencv-mingw\install "MinGW Makefiles"
```
手动构建:
```bat
mkdir build-windows
cd build-windows
cmake .. -G "MinGW Makefiles" -DCMAKE_PREFIX_PATH=C:\Qt\6.6.0\mingw_64 -DOpenCV_DIR=C:\opencv-mingw\install
cmake --build . --config Release
```
MinGW 生成的 exe 通常位于:
```text
build-windows\QtOpenCVImageTool.exe
```
### 运行和发布
构建出来的 `QtOpenCVImageTool.exe` 运行时需要 Qt 和 OpenCV 的 DLL。开发阶段可以直接在 Qt Creator 中运行;如果要单独拷贝给别人运行,需要把依赖 DLL 一起放到 exe 目录。
MSVC Release 示例:
```bat
cd build-windows\Release
C:\Qt\6.6.0\msvc2019_64\bin\windeployqt.exe QtOpenCVImageTool.exe
copy C:\opencv\build\x64\vc16\bin\opencv_world*.dll .
```
如果 OpenCV 不是 `opencv_world*.dll`,则复制对应的 `opencv_*.dll` 到 exe 所在目录。
MinGW 示例:
```bat
cd build-windows
C:\Qt\6.6.0\mingw_64\bin\windeployqt.exe QtOpenCVImageTool.exe
copy C:\opencv-mingw\bin\opencv_*.dll .
```
### 常见问题
1. `Could not find Qt6`
说明 `CMAKE_PREFIX_PATH` 没有指向 Qt 安装目录。请确认路径类似:
```text
C:\Qt\6.6.0\msvc2019_64
```
2. `Could not find OpenCV`
说明 `OpenCV_DIR` 没有指向包含 `OpenCVConfig.cmake` 的目录。请搜索 `OpenCVConfig.cmake`,并把它所在目录传给 CMake。
3. 程序启动时报缺少 DLL
请运行 `windeployqt`,并把 OpenCV 的 DLL 复制到 exe 所在目录。
4. 链接时报 MSVC/MinGW 相关错误
通常是 Qt、OpenCV、编译器不匹配。MSVC 工程必须使用 MSVC 版 Qt 和 MSVC 版 OpenCV;MinGW 工程必须使用 MinGW 版 Qt 和 MinGW 版 OpenCV。
## WSL 中交叉编译 Windows 程序
WSL 里不能使用 Linux 版 Qt/OpenCV 直接生成 Windows exe,必须准备 Windows 目标库。推荐使用 MinGW-w64 作为交叉编译器,并准备同为 MinGW-w64 目标的 Qt 和 OpenCV。
需要的组件:
- `x86_64-w64-mingw32-g++`
- Windows/MinGW 目标 Qt,目录中应包含 `Qt6Config.cmake` 或 `Qt5Config.cmake`
- Windows/MinGW 目标 OpenCV,目录中应包含 `OpenCVConfig.cmake`
构建脚本:
```bash
export QT_MINGW_PREFIX=/opt/mxe/usr/x86_64-w64-mingw32.shared/qt6
export OpenCV_DIR=/opt/mxe/usr/x86_64-w64-mingw32.shared/lib/cmake/opencv4
./build_wsl_windows.sh
```
如果使用的是自己编译或复制来的 Windows 目标 Qt/OpenCV,把上面两个路径换成实际路径即可。
## 说明
本示例中的分类属于简单规则分类,适合作为课程作业演示:根据图像整体亮度判断“偏亮/偏暗/亮度适中”,根据 BGR 平均值判断主色。若需要更高精度分类,可替换为训练好的 OpenCV DNN 或传统机器学习模型。
- `main.cpp`:应用入口,创建并显示主窗口
- `MainWindow.h`:主窗口和图片标签类声明
- `MainWindow.cpp`:菜单、工具栏、图片显示和处理逻辑
- `CMakeLists.txt`:Qt Widgets CMake 构建配置
- `build-windows.ps1`:Windows 一键构建与打包脚本
- `readme.md`:项目说明文档