diff --git a/.gitea/workflows/build-windows-release.yml b/.gitea/workflows/build-windows-release.yml index e7fb3b5..179dff5 100644 --- a/.gitea/workflows/build-windows-release.yml +++ b/.gitea/workflows/build-windows-release.yml @@ -13,218 +13,177 @@ permissions: jobs: build-windows-release: - name: Build Windows x64 Release (MSVC + Qt) - # Windows runner 已注册标签:windows-latest、windows-2022、self-hosted;均为 host 模式。 - runs-on: windows-2022 + name: Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) + runs-on: ubuntu-latest + container: fedora:latest env: BUILD_TYPE: Release - QT_VERSION: 6.7.3 - QT_ARCH: win64_msvc2022_64 - QT_DIR_NAME: msvc2022_64 - PACKAGE_BASENAME: chengnan-windows-x64-msvc - PACKAGE_NAME: chengnan-windows-x64-msvc + PACKAGE_BASENAME: chengnan-windows-x64-mingw steps: - - name: Prepare source - shell: powershell + - name: Install cross build dependencies 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 + dnf install -y \ + git \ + curl \ + jq \ + zip \ + unzip \ + python3 \ + cmake \ + ninja-build \ + mingw64-gcc-c++ \ + mingw64-qt6-qtbase \ + mingw64-qt6-qtbase-devel \ + mingw64-qt6-qtimageformats \ + mingw64-opencv - $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 + - name: Checkout + uses: actions/checkout@v4 - $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 official Qt for MSVC - shell: powershell + - name: Configure cross build run: | - $ErrorActionPreference = 'Stop' - $qtRoot = Join-Path $env:RUNNER_TEMP 'qt-msvc' - $qtPrefix = Join-Path $qtRoot "$env:QT_VERSION\$env:QT_DIR_NAME" - $windeployqt = Join-Path $qtPrefix 'bin\windeployqt.exe' - if (Test-Path $windeployqt) { - Write-Host "Qt already installed: $qtPrefix" - exit 0 - } + x86_64-w64-mingw32-cmake -S . -B build-windows -G Ninja \ + -DCMAKE_BUILD_TYPE="$BUILD_TYPE" - $uvExe = Join-Path $env:RUNNER_TEMP 'uv.exe' - if (-not (Test-Path $uvExe)) { - $uvUrl = 'https://github.com/astral-sh/uv/releases/latest/download/uv-x86_64-pc-windows-msvc.zip' - $uvZip = Join-Path $env:RUNNER_TEMP 'uv.zip' - $uvExtract = Join-Path $env:RUNNER_TEMP 'uv-extract' - if (Test-Path $uvExtract) { Remove-Item -Recurse -Force $uvExtract } - Write-Host "Downloading uv from $uvUrl" - Invoke-WebRequest -Uri $uvUrl -OutFile $uvZip - Expand-Archive -Path $uvZip -DestinationPath $uvExtract -Force - $uvFound = Get-ChildItem -Path $uvExtract -Recurse -Filter 'uv.exe' | Select-Object -First 1 - if (-not $uvFound) { throw 'uv.exe was not found in downloaded archive.' } - Copy-Item $uvFound.FullName $uvExe -Force - } + - name: Build + run: cmake --build build-windows --config "$BUILD_TYPE" --parallel - & $uvExe tool run --from aqtinstall aqt install-qt windows desktop $env:QT_VERSION $env:QT_ARCH -O $qtRoot -m qtimageformats - if ($LASTEXITCODE -ne 0) { throw "aqt Qt installation failed, exit code: $LASTEXITCODE" } - if (-not (Test-Path $windeployqt)) { throw "Qt installation finished but windeployqt was not found: $windeployqt" } - Write-Host "Qt installed: $qtPrefix" - - - name: Configure, build, and deploy with MSVC - shell: powershell + - name: Package Windows app run: | - $ErrorActionPreference = 'Stop' - $src = Join-Path $env:RUNNER_TEMP 'chengnan-work' - $qtRoot = Join-Path $env:RUNNER_TEMP 'qt-msvc' - $qtPrefix = Join-Path $qtRoot "$env:QT_VERSION\$env:QT_DIR_NAME" + set -euo pipefail + root="/usr/x86_64-w64-mingw32/sys-root/mingw" + dist="dist-windows/chengnan" + rm -rf "$dist" artifacts + mkdir -p "$dist/platforms" "$dist/imageformats" artifacts - $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' - if (-not (Test-Path $vswhere)) { throw "vswhere not found: $vswhere. Install Visual Studio 2022 Build Tools with Desktop development with C++." } - $vsPath = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath - if ([string]::IsNullOrWhiteSpace($vsPath)) { throw 'Visual Studio 2022 C++ build tools were not found. Install Desktop development with C++.' } - $vsDevCmd = Join-Path $vsPath 'Common7\Tools\VsDevCmd.bat' - if (-not (Test-Path $vsDevCmd)) { throw "VsDevCmd.bat not found: $vsDevCmd" } + cp build-windows/chengnan.exe "$dist/" + cp "$root/bin/Qt6Core.dll" "$dist/" + cp "$root/bin/Qt6Gui.dll" "$dist/" + cp "$root/bin/Qt6Widgets.dll" "$dist/" + cp "$root/bin/libgcc_s_seh-1.dll" "$dist/" + cp "$root/bin/libstdc++-6.dll" "$dist/" + cp "$root/bin/libwinpthread-1.dll" "$dist/" + cp "$root/lib/qt6/plugins/platforms/qwindows.dll" "$dist/platforms/" + cp "$root/lib/qt6/plugins/imageformats/"*.dll "$dist/imageformats/" + cp "$root/bin/opencv_"*.dll "$dist/" + install -m 0644 readme.md "$dist/readme.md" - $vsCmake = Join-Path $vsPath 'Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin' - if (Test-Path (Join-Path $vsCmake 'cmake.exe')) { $env:PATH = "$vsCmake;$env:PATH" } - if (-not (Get-Command cmake -ErrorAction SilentlyContinue)) { throw 'cmake was not found on PATH or in Visual Studio bundled CMake.' } + cat > "$dist/README.txt" <<'EOF' + chengnan Windows x64 package - $buildDir = Join-Path $src 'build-windows' - $distDir = Join-Path $src 'dist-windows\chengnan' - $script = Join-Path $src 'build-windows.ps1' - $cmd = "`"$vsDevCmd`" -arch=x64 -host_arch=x64 && powershell -NoProfile -ExecutionPolicy Bypass -File `"$script`" -QtPrefix `"$qtPrefix`" -BuildDir `"$buildDir`" -DistDir `"$distDir`" -Generator `"Visual Studio 17 2022`" -Arch x64 -Config Release" - Write-Host "Building with Visual Studio at: $vsPath" - Write-Host "Using Qt: $qtPrefix" - & cmd.exe /c $cmd - if ($LASTEXITCODE -ne 0) { throw "MSVC build failed, exit code: $LASTEXITCODE" } + Usage: + 1. Extract the whole directory. + 2. Double-click chengnan.exe to run. - $readme = Join-Path $distDir 'README.txt' - @( - '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 MSVC + official Qt.', - '- Do not copy chengnan.exe alone; keep DLLs and Qt plugin directories together.' - ) | Out-File -FilePath $readme -Encoding ascii + Note: + - This package is cross-built on Linux with MinGW + Qt + OpenCV. + - Do not copy chengnan.exe alone; keep DLLs and Qt plugin directories together. + EOF - - 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" + short_sha="${GITHUB_SHA::10}" + if [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then + version="$GITHUB_REF_NAME" + else + version="build-$short_sha" + fi + package="$PACKAGE_BASENAME-$version.zip" + (cd dist-windows && zip -r "../artifacts/$package" chengnan) + sha256sum "artifacts/$package" > "artifacts/$package.sha256" + printf 'VERSION=%s\n' "$version" >> "$GITHUB_ENV" + printf 'PACKAGE=%s\n' "$package" >> "$GITHUB_ENV" - 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" + set -euo pipefail + test -s "artifacts/$PACKAGE" + test -s "artifacts/$PACKAGE.sha256" + unzip -l "artifacts/$PACKAGE" | grep -q 'chengnan/chengnan.exe' + unzip -l "artifacts/$PACKAGE" | grep -q 'chengnan/platforms/qwindows.dll' + unzip -l "artifacts/$PACKAGE" | grep -q 'chengnan/opencv_.*\.dll' + sha256sum -c "artifacts/$PACKAGE.sha256" - 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.' } + set -euo pipefail + token="${RELEASE_TOKEN:-${GITHUB_TOKEN:-}}" + if [ -z "$token" ]; then + echo 'Missing release token. Configure RELEASE_TOKEN in repository secrets or ensure GITHUB_TOKEN is available.' >&2 + exit 1 + fi - $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" + server_url="${GITHUB_SERVER_URL%/}" + api_base="$server_url/api/v1/repos/$GITHUB_REPOSITORY" + tag_name="$VERSION" + if [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then + prerelease=false + release_name="$GITHUB_REF_NAME" + else + prerelease=true + release_name="chengnan ${GITHUB_SHA::10}" + fi - $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' } + release_payload=$(jq -n \ + --arg tag_name "$tag_name" \ + --arg target_commitish "$GITHUB_SHA" \ + --arg name "$release_name" \ + --arg body "Automated Windows x64 MinGW build from Linux Gitea Actions." \ + --argjson prerelease "$prerelease" \ + '{tag_name:$tag_name,target_commitish:$target_commitish,name:$name,body:$body,draft:false,prerelease:$prerelease}') - $releasePayload = @{ - tag_name = $tagName - target_commitish = $env:GITHUB_SHA - name = $releaseName - body = "Automated Windows x64 MSVC build from Gitea Actions.`n" - draft = $false - prerelease = $isPrerelease - } | ConvertTo-Json -Depth 5 + status=$(curl --silent --show-error --location \ + --header "Authorization: token $token" \ + --header 'Content-Type: application/json' \ + --write-out '%{http_code}' \ + --output release.json \ + --data "$release_payload" \ + "$api_base/releases") - 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 - } + if [ "$status" != "200" ] && [ "$status" != "201" ]; then + curl --silent --show-error --location \ + --header "Authorization: token $token" \ + --output release.json \ + "$api_base/releases/tags/$tag_name" + fi - 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 - } - } - } + release_id=$(jq -r '.id' release.json) + if [ -z "$release_id" ] || [ "$release_id" = "null" ]; then + echo 'Failed to resolve release id.' >&2 + cat release.json >&2 + exit 1 + fi - 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 } + upload_asset() { + local path="$1" + local name + name=$(basename "$path") + curl --silent --show-error --location \ + --header "Authorization: token $token" \ + "$api_base/releases/$release_id/assets" > assets.json + jq -r --arg name "$name" '.[] | select(.name == $name) | .id' assets.json | while read -r asset_id; do + [ -n "$asset_id" ] && curl --silent --show-error --location \ + --request DELETE \ + --header "Authorization: token $token" \ + "$api_base/releases/assets/$asset_id" >/dev/null + done + + status=$(curl --silent --show-error --location \ + --header "Authorization: token $token" \ + --form "attachment=@$path;filename=$name" \ + --write-out '%{http_code}' \ + --output upload-response.json \ + "$api_base/releases/$release_id/assets?name=$(python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1]))' "$name")") + if [ "$status" != "200" ] && [ "$status" != "201" ]; then + echo "Upload release asset failed, HTTP $status: $name" >&2 + cat upload-response.json >&2 exit 1 - } - Write-Host "Uploaded release asset: $name" + fi + echo "Uploaded release asset: $name" } - Upload-Asset $zipPath - Upload-Asset $shaPath - Write-Host "Release assets uploaded to $serverUrl/$repo/releases/tag/$tagName" + upload_asset "artifacts/$PACKAGE" + upload_asset "artifacts/$PACKAGE.sha256" + echo "Release assets uploaded to $server_url/$GITHUB_REPOSITORY/releases/tag/$tag_name" diff --git a/CMakeLists.txt b/CMakeLists.txt index 136e3f9..cef20e7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,6 +8,8 @@ set(CMAKE_AUTOMOC ON) set(CMAKE_AUTOUIC OFF) set(CMAKE_AUTORCC OFF) +find_package(OpenCV REQUIRED COMPONENTS core imgproc imgcodecs) + find_package(Qt6 QUIET COMPONENTS Widgets) if (Qt6_FOUND) qt_add_executable(chengnan @@ -15,7 +17,7 @@ if (Qt6_FOUND) MainWindow.h MainWindow.cpp ) - target_link_libraries(chengnan PRIVATE Qt6::Widgets) + target_link_libraries(chengnan PRIVATE Qt6::Widgets ${OpenCV_LIBS}) else() find_package(Qt5 REQUIRED COMPONENTS Widgets) add_executable(chengnan @@ -23,9 +25,11 @@ else() MainWindow.h MainWindow.cpp ) - target_link_libraries(chengnan PRIVATE Qt5::Widgets) + target_link_libraries(chengnan PRIVATE Qt5::Widgets ${OpenCV_LIBS}) endif() +target_include_directories(chengnan PRIVATE ${OpenCV_INCLUDE_DIRS}) + target_compile_definitions(chengnan PRIVATE CHENGNAN_APP_VERSION="${PROJECT_VERSION}" ) diff --git a/MainWindow.cpp b/MainWindow.cpp index a8a3294..71d40f6 100644 --- a/MainWindow.cpp +++ b/MainWindow.cpp @@ -10,12 +10,119 @@ #include #include #include +#include #include +#include #include +#include #include +#include + +#include #include #include +#include +#include + +namespace { + +cv::Mat qImageToMat(const QImage &image) +{ + const QImage rgba = image.convertToFormat(QImage::Format_RGBA8888); + cv::Mat mat(rgba.height(), rgba.width(), CV_8UC4, const_cast(rgba.constBits()), rgba.bytesPerLine()); + return mat.clone(); +} + +QImage matToQImage(const cv::Mat &mat) +{ + if (mat.empty()) { + return {}; + } + + cv::Mat rgba; + if (mat.channels() == 1) { + cv::cvtColor(mat, rgba, cv::COLOR_GRAY2RGBA); + } else if (mat.channels() == 3) { + cv::cvtColor(mat, rgba, cv::COLOR_BGR2RGBA); + } else { + cv::cvtColor(mat, rgba, cv::COLOR_BGRA2RGBA); + } + + return QImage(rgba.data, rgba.cols, rgba.rows, static_cast(rgba.step), QImage::Format_RGBA8888).copy(); +} + +QImage extractObjectImage(const QImage &image) +{ + const cv::Mat rgba = qImageToMat(image); + cv::Mat gray; + cv::cvtColor(rgba, gray, cv::COLOR_RGBA2GRAY); + cv::GaussianBlur(gray, gray, cv::Size(5, 5), 0.0); + + cv::Mat edges; + cv::Canny(gray, edges, 60, 160); + + std::vector> contours; + cv::findContours(edges, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); + + cv::Mat output = rgba.clone(); + cv::cvtColor(output, output, cv::COLOR_RGBA2BGRA); + int count = 0; + for (const auto &contour : contours) { + const double area = cv::contourArea(contour); + if (area < 120.0) { + continue; + } + const cv::Rect rect = cv::boundingRect(contour); + cv::rectangle(output, rect, cv::Scalar(0, 0, 255, 255), 2); + ++count; + } + + cv::putText(output, + "objects: " + std::to_string(count), + cv::Point(16, 32), + cv::FONT_HERSHEY_SIMPLEX, + 0.9, + cv::Scalar(0, 0, 255, 255), + 2); + return matToQImage(output); +} + +QImage classifyImageByOpenCv(const QImage &image) +{ + const cv::Mat rgba = qImageToMat(image); + cv::Mat gray; + cv::cvtColor(rgba, gray, cv::COLOR_RGBA2GRAY); + + cv::Mat edges; + cv::Canny(gray, edges, 80, 180); + const double brightness = cv::mean(gray)[0]; + const double edgeRatio = static_cast(cv::countNonZero(edges)) / static_cast(gray.total()); + + std::string label; + if (brightness < 80.0) { + label = "class: dark image"; + } else if (edgeRatio > 0.12) { + label = "class: rich edges"; + } else { + label = "class: bright smooth image"; + } + + cv::Mat output = rgba.clone(); + cv::cvtColor(output, output, cv::COLOR_RGBA2BGRA); + const int boxWidth = std::max(1, std::min(520, output.cols - 16)); + cv::rectangle(output, cv::Rect(8, 8, boxWidth, 52), cv::Scalar(0, 0, 0, 180), cv::FILLED); + cv::putText(output, + label, + cv::Point(18, 42), + cv::FONT_HERSHEY_SIMPLEX, + 0.8, + cv::Scalar(0, 255, 255, 255), + 2); + return matToQImage(output); +} + +} // namespace ImageLabel::ImageLabel(QWidget *parent) : QLabel(parent) @@ -45,8 +152,8 @@ MainWindow::MainWindow(QWidget *parent) createCentralWidget(); updateActions(); - setWindowTitle(tr("chengnan 图片查看器")); - resize(1100, 720); + setWindowTitle(tr("chengnan 图片处理工具")); + resize(1200, 720); statusBar()->showMessage(tr("就绪")); } @@ -101,6 +208,12 @@ void MainWindow::createActions() invertAction_ = new QAction(tr("反色"), this); connect(invertAction_, &QAction::triggered, this, &MainWindow::invertColors); + + extractAction_ = new QAction(tr("目标提取"), this); + connect(extractAction_, &QAction::triggered, this, &MainWindow::extractObjects); + + classifyAction_ = new QAction(tr("简单分类"), this); + connect(classifyAction_, &QAction::triggered, this, &MainWindow::classifyImage); } void MainWindow::createMenus() @@ -126,6 +239,9 @@ void MainWindow::createMenus() processMenu->addSeparator(); processMenu->addAction(grayscaleAction_); processMenu->addAction(invertAction_); + processMenu->addSeparator(); + processMenu->addAction(extractAction_); + processMenu->addAction(classifyAction_); } void MainWindow::createToolbar() @@ -152,18 +268,35 @@ void MainWindow::createToolbar() toolbar->addAction(rotateRightAction_); toolbar->addAction(grayscaleAction_); toolbar->addAction(invertAction_); + toolbar->addAction(extractAction_); + toolbar->addAction(classifyAction_); } void MainWindow::createCentralWidget() { - imageLabel_ = new ImageLabel(this); - connect(imageLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow); + originalLabel_ = new ImageLabel(this); + processedLabel_ = new ImageLabel(this); + originalLabel_->setText(tr("处理前图像")); + processedLabel_->setText(tr("处理后图像")); + connect(originalLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow); + connect(processedLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow); - scrollArea_ = new QScrollArea(this); - scrollArea_->setBackgroundRole(QPalette::Dark); - scrollArea_->setWidget(imageLabel_); - scrollArea_->setWidgetResizable(true); - setCentralWidget(scrollArea_); + originalScrollArea_ = new QScrollArea(this); + originalScrollArea_->setBackgroundRole(QPalette::Dark); + originalScrollArea_->setWidget(originalLabel_); + originalScrollArea_->setWidgetResizable(true); + + processedScrollArea_ = new QScrollArea(this); + processedScrollArea_->setBackgroundRole(QPalette::Dark); + processedScrollArea_->setWidget(processedLabel_); + processedScrollArea_->setWidgetResizable(true); + + auto *splitter = new QSplitter(Qt::Horizontal, this); + splitter->addWidget(originalScrollArea_); + splitter->addWidget(processedScrollArea_); + splitter->setStretchFactor(0, 1); + splitter->setStretchFactor(1, 1); + setCentralWidget(splitter); } void MainWindow::openImage() @@ -236,7 +369,7 @@ void MainWindow::fitToWindow() return; } - const QSize viewportSize = scrollArea_->viewport()->size(); + const QSize viewportSize = processedScrollArea_->viewport()->size(); const QSize imageSize = currentImage_.size(); if (imageSize.isEmpty()) { return; @@ -290,20 +423,35 @@ void MainWindow::flipVertical() void MainWindow::grayscale() { - if (!ensureImageLoaded(tr("灰度化"))) { - return; - } - applyTransformedImage(currentImage_.convertToFormat(QImage::Format_Grayscale8)); + processImageInThread(tr("灰度化"), tr("灰度化完成,可保存结果"), [](QImage image) { + cv::Mat rgba = qImageToMat(image); + cv::Mat gray; + cv::cvtColor(rgba, gray, cv::COLOR_RGBA2GRAY); + return matToQImage(gray); + }); } void MainWindow::invertColors() { - if (!ensureImageLoaded(tr("反色"))) { - return; - } - QImage image = currentImage_.convertToFormat(QImage::Format_ARGB32); - image.invertPixels(QImage::InvertRgb); - applyTransformedImage(image); + processImageInThread(tr("反色"), tr("反色完成,可保存结果"), [](QImage image) { + QImage result = image.convertToFormat(QImage::Format_ARGB32); + result.invertPixels(QImage::InvertRgb); + return result; + }); +} + +void MainWindow::extractObjects() +{ + processImageInThread(tr("目标提取"), tr("目标提取完成,红框为提取到的目标"), [](QImage image) { + return extractObjectImage(image); + }); +} + +void MainWindow::classifyImage() +{ + processImageInThread(tr("简单分类"), tr("简单分类完成,结果已标注在图像上"), [](QImage image) { + return classifyImageByOpenCv(image); + }); } void MainWindow::updateZoomFromSlider(int value) @@ -317,43 +465,55 @@ void MainWindow::updateZoomFromSlider(int value) void MainWindow::setImage(const QImage &image, const QString &path) { - currentImage_ = image.convertToFormat(QImage::Format_ARGB32); + originalImage_ = image.convertToFormat(QImage::Format_ARGB32); + currentImage_ = originalImage_; currentPath_ = path; setZoomFactor(1.0); updateActions(); const QFileInfo info(path); setWindowTitle(path.isEmpty() - ? tr("chengnan 图片查看器") - : tr("%1 - chengnan 图片查看器").arg(info.fileName())); + ? 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("打开一张图片开始查看")); + originalLabel_->setPixmap(QPixmap()); + processedLabel_->setPixmap(QPixmap()); + originalLabel_->setText(tr("处理前图像")); + processedLabel_->setText(tr("处理后图像")); return; } - const QSize scaledSize = currentImage_.size() * zoomFactor_; - const QPixmap pixmap = QPixmap::fromImage(currentImage_).scaled( + updateSingleView(originalLabel_, originalImage_); + updateSingleView(processedLabel_, currentImage_); + + const int sliderValue = static_cast(zoomFactor_ * 100.0); + if (zoomSlider_->value() != sliderValue) { + zoomSlider_->blockSignals(true); + zoomSlider_->setValue(sliderValue); + zoomSlider_->blockSignals(false); + } + + statusBar()->showMessage(tr("缩放:%1%").arg(sliderValue)); +} + +void MainWindow::updateSingleView(ImageLabel *label, const QImage &image) +{ + const QSize scaledSize( + std::max(1, static_cast(std::round(image.width() * zoomFactor_))), + std::max(1, static_cast(std::round(image.height() * zoomFactor_)))); + const QPixmap pixmap = QPixmap::fromImage(image).scaled( scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); - imageLabel_->setText(QString()); - imageLabel_->setPixmap(pixmap); - imageLabel_->resize(pixmap.size()); - - if (zoomSlider_->value() != static_cast(zoomFactor_ * 100.0)) { - zoomSlider_->blockSignals(true); - zoomSlider_->setValue(static_cast(zoomFactor_ * 100.0)); - zoomSlider_->blockSignals(false); - } - - statusBar()->showMessage(tr("缩放:%1%").arg(static_cast(zoomFactor_ * 100.0))); + label->setText(QString()); + label->setPixmap(pixmap); + label->resize(pixmap.size()); } void MainWindow::setZoomFactor(double factor) @@ -362,12 +522,45 @@ void MainWindow::setZoomFactor(double factor) updateImageView(); } -void MainWindow::applyTransformedImage(const QImage &image) +void MainWindow::applyTransformedImage(const QImage &image, const QString &message) { currentImage_ = image.convertToFormat(QImage::Format_ARGB32); updateImageView(); updateActions(); - statusBar()->showMessage(tr("处理完成,可保存结果"), 3000); + statusBar()->showMessage(message.isEmpty() ? tr("处理完成,可保存结果") : message, 3000); +} + +void MainWindow::processImageInThread(const QString &actionName, + const QString &doneMessage, + const std::function &processor) +{ + if (!ensureImageLoaded(actionName)) { + return; + } + + const QImage input = currentImage_; + auto result = std::make_shared(); + auto error = std::make_shared(); + QThread *thread = QThread::create([input, result, error, processor]() { + try { + *result = processor(input); + } catch (const cv::Exception &ex) { + *error = QString::fromLocal8Bit(ex.what()); + } catch (const std::exception &ex) { + *error = QString::fromLocal8Bit(ex.what()); + } + }); + + statusBar()->showMessage(tr("正在处理:%1 ...").arg(actionName)); + connect(thread, &QThread::finished, this, [this, thread, result, error, doneMessage]() { + thread->deleteLater(); + if (!error->isEmpty() || result->isNull()) { + QMessageBox::warning(this, tr("处理失败"), error->isEmpty() ? tr("处理结果为空。") : *error); + return; + } + applyTransformedImage(*result, doneMessage); + }); + thread->start(); } void MainWindow::updateActions() @@ -385,6 +578,8 @@ void MainWindow::updateActions() flipVerticalAction_->setEnabled(hasImage); grayscaleAction_->setEnabled(hasImage); invertAction_->setEnabled(hasImage); + extractAction_->setEnabled(hasImage); + classifyAction_->setEnabled(hasImage); zoomSlider_->setEnabled(hasImage); } @@ -407,7 +602,7 @@ bool MainWindow::writeImageToPath(const QString &path) } currentPath_ = path; - setWindowTitle(tr("%1 - chengnan 图片查看器").arg(QFileInfo(path).fileName())); + setWindowTitle(tr("%1 - chengnan 图片处理工具").arg(QFileInfo(path).fileName())); statusBar()->showMessage(tr("已保存:%1").arg(path), 5000); return true; } diff --git a/MainWindow.h b/MainWindow.h index 3064e9a..695fc1f 100644 --- a/MainWindow.h +++ b/MainWindow.h @@ -7,6 +7,7 @@ #include #include #include +#include class QAction; class QMenu; @@ -48,6 +49,8 @@ private Q_SLOTS: void flipVertical(); void grayscale(); void invertColors(); + void extractObjects(); + void classifyImage(); void updateZoomFromSlider(int value); private: @@ -57,16 +60,21 @@ private: void createCentralWidget(); void setImage(const QImage &image, const QString &path = QString()); void updateImageView(); + void updateSingleView(ImageLabel *label, const QImage &image); void setZoomFactor(double factor); - void applyTransformedImage(const QImage &image); + void applyTransformedImage(const QImage &image, const QString &message = QString()); + void processImageInThread(const QString &actionName, const QString &doneMessage, const std::function &processor); void updateActions(); bool ensureImageLoaded(const QString &actionName) const; bool writeImageToPath(const QString &path); - ImageLabel *imageLabel_ = nullptr; - QScrollArea *scrollArea_ = nullptr; + ImageLabel *originalLabel_ = nullptr; + ImageLabel *processedLabel_ = nullptr; + QScrollArea *originalScrollArea_ = nullptr; + QScrollArea *processedScrollArea_ = nullptr; QSlider *zoomSlider_ = nullptr; + QImage originalImage_; QImage currentImage_; QString currentPath_; double zoomFactor_ = 1.0; @@ -85,6 +93,8 @@ private: QAction *flipVerticalAction_ = nullptr; QAction *grayscaleAction_ = nullptr; QAction *invertAction_ = nullptr; + QAction *extractAction_ = nullptr; + QAction *classifyAction_ = nullptr; }; #endif // MAINWINDOW_H diff --git a/build-windows.ps1 b/build-windows.ps1 deleted file mode 100644 index c06961c..0000000 --- a/build-windows.ps1 +++ /dev/null @@ -1,100 +0,0 @@ -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" diff --git a/readme.md b/readme.md index 394017c..b60b1a6 100644 --- a/readme.md +++ b/readme.md @@ -2,34 +2,52 @@ 项目链接: -`chengnan` 是一个轻量级 Windows 图片查看器 / 简单图片处理工具,使用 **Qt Widgets + CMake + C++17** 开发。 +`chengnan` 是一个 Windows 图像显示与处理课程项目,使用 **Qt Widgets + OpenCV + CMake + C++17** 开发。 + +## 作业要求对应情况 + +- 使用 Qt 设计界面:已使用 Qt Widgets 实现菜单栏、工具栏和双栏图像显示界面。 +- 打开图片、保存图片、另存图片:已实现。 +- 缩放、平移、旋转: + - 缩放:工具栏滑块、放大、缩小、原始大小、双击适配窗口。 + - 平移:图片位于 `QScrollArea` 中,放大后可通过滚动条平移查看。 + - 旋转:左旋 90°、右旋 90°。 +- 图片处理:灰度化、反色、目标提取、简单分类。 +- 处理前后对比:主界面左右两个 `QWidget` 区域分别显示处理前和处理后图像。 +- 显示方式:使用 Qt Widgets 显示图片,未使用 `cv::imshow`。 +- OpenCV 处理线程:灰度化、反色、目标提取、简单分类通过 Qt 线程执行,避免处理时阻塞界面。 +- Windows 应用构建发布:`.gitea/workflows/build-windows-release.yml` 会在 Gitea Actions 的 Linux Runner 中交叉构建 Windows x64 程序并上传 Release 附件。 ## 功能 当前实现: - 打开图片:PNG、JPG、JPEG、BMP、GIF、WebP 等 Qt 支持的格式 -- 保存当前图片 +- 保存当前处理后图片 - 另存为 PNG / JPG / BMP 等格式 -- 图片显示:使用 Qt Widgets,不使用 OpenCV 窗口 +- 处理前 / 处理后双栏对比显示 - 缩放:工具栏滑块、放大、缩小、原始大小 +- 平移:放大后使用滚动条移动查看区域 - 双击图片适配窗口 - 旋转:左旋 90°、右旋 90° - 翻转:水平翻转、垂直翻转 -- 简单处理:灰度化、反色 +- OpenCV 图片处理:灰度化、目标提取、简单分类 +- 其它处理:反色 ## 文件结构 ```text chengnan/ +├── .gitea/workflows/build-windows-release.yml ├── CMakeLists.txt ├── MainWindow.cpp ├── MainWindow.h -├── build-windows.ps1 ├── main.cpp └── readme.md ``` +除工作流和 `readme.md` 外,工程根目录只保留 `CMakeLists.txt`、`main.cpp`、`MainWindow.h`、`MainWindow.cpp` 四个文件。 + ## Windows 编译需要的工具 推荐环境:Windows 10 / Windows 11 x64。 @@ -47,18 +65,16 @@ chengnan/ 3. **Qt 6 或 Qt 5,包含 Widgets 模块** - 下载: - 推荐安装 Qt 6.x 的 MSVC 64-bit 套件,例如 `msvc2019_64` 或 `msvc2022_64`。 - - 项目不依赖 OpenCV。 -4. **Visual Studio 2022 Build Tools 或 Visual Studio 2022** +4. **OpenCV 4.x Windows 预编译包** + - 下载: + - 解压后 CMake 需要能找到 OpenCV 的 `build` 目录,例如 `C:\opencv\build`。 + +5. **Visual Studio 2022 Build Tools 或 Visual Studio 2022** - 下载: - 需要安装组件:`使用 C++ 的桌面开发`。 - 提供 MSVC 编译器和 Windows SDK。 -可选工具: - -- **Ninja**: -- 如果使用 Ninja,可以把 `build-windows.ps1` 的 `-Generator` 参数改成 `Ninja`。 - ## 获取源码 ```powershell @@ -66,63 +82,43 @@ 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 -``` - ## 手动构建 -如果不使用脚本,也可以手动执行: +在已配置 Visual Studio C++ 编译环境的 PowerShell 或 “x64 Native Tools Command Prompt for VS 2022” 中执行: ```powershell -cmake -S . -B build-windows -G "Visual Studio 17 2022" -A x64 -DCMAKE_PREFIX_PATH="C:\Qt\6.7.2\msvc2019_64" +cmake -S . -B build-windows -G "Visual Studio 17 2022" -A x64 -DCMAKE_PREFIX_PATH="C:\Qt\6.7.3\msvc2022_64;C:\opencv\build" 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 +C:\Qt\6.7.3\msvc2022_64\bin\windeployqt.exe --release --no-translations build-windows\Release\chengnan.exe ``` +还需要把 OpenCV 的运行库 DLL(例如 `opencv_world4100.dll`)复制到 `chengnan.exe` 同目录。 + +## Gitea Actions / GitHub Actions 风格工作流 + +仓库中的 `.gitea/workflows/build-windows-release.yml` 使用 Linux Runner 的 Fedora 容器交叉构建 Windows x64 应用并发布 Release 附件: + +- 安装 MinGW-w64、Qt MinGW、OpenCV MinGW 依赖 +- 使用 `x86_64-w64-mingw32-cmake` 配置 Windows 目标程序 +- 使用 Ninja 在 Linux 上交叉编译生成 `chengnan.exe` +- 打包 `chengnan.exe`、Qt DLL、OpenCV DLL、Qt 插件目录 +- 上传 `.zip` 和 `.sha256` 到仓库 Release + +发布上传使用仓库 Secret:`RELEASE_TOKEN`。如果没有配置该 Secret,工作流会尝试使用运行环境提供的 `GITHUB_TOKEN`。 + ## 常见问题 ### 找不到 Qt -确认 `-QtPrefix` 指向 Qt 套件目录,而不是 Qt 根目录。例如应使用: +确认 CMake 的 `CMAKE_PREFIX_PATH` 包含 Qt 套件目录,而不是 Qt 根目录。例如应使用: ```text -C:\Qt\6.7.2\msvc2019_64 +C:\Qt\6.7.3\msvc2022_64 ``` 不要写成: @@ -131,19 +127,28 @@ C:\Qt\6.7.2\msvc2019_64 C:\Qt ``` +### 找不到 OpenCV + +确认 CMake 的 `CMAKE_PREFIX_PATH` 包含 OpenCV 的 `build` 目录。例如: + +```text +C:\opencv\build +``` + +该目录下通常能找到 `OpenCVConfig.cmake`。 + ### 找不到 MSVC 编译器 -请安装 Visual Studio 2022 的 `使用 C++ 的桌面开发`,然后在 “x64 Native Tools Command Prompt for VS 2022” 或已配置 VS 环境的 PowerShell 里运行构建脚本。 +请安装 Visual Studio 2022 的 `使用 C++ 的桌面开发`,然后在 “x64 Native Tools Command Prompt for VS 2022” 或已配置 VS 环境的 PowerShell 里运行构建命令。 ### exe 复制到其它电脑无法运行 -请运行 `build-windows.ps1`,并整体复制 `dist-windows\chengnan` 文件夹,不要只复制单个 `chengnan.exe`。 +不要只复制单个 `chengnan.exe`。需要同时复制 Qt / OpenCV DLL 和 Qt 插件目录,或直接使用 Gitea Actions 发布的 zip 附件。 ## 开发说明 - `main.cpp`:应用入口,创建并显示主窗口 - `MainWindow.h`:主窗口和图片标签类声明 -- `MainWindow.cpp`:菜单、工具栏、图片显示和处理逻辑 -- `CMakeLists.txt`:Qt Widgets CMake 构建配置 -- `build-windows.ps1`:Windows 一键构建与打包脚本 +- `MainWindow.cpp`:菜单、工具栏、图片显示、OpenCV 图像处理和 Qt 线程逻辑 +- `CMakeLists.txt`:Qt Widgets + OpenCV CMake 构建配置 - `readme.md`:项目说明文档