Compare commits
15 Commits
build-081a
...
f915ba24bc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f915ba24bc | ||
|
|
7fb902567e | ||
|
|
353a175306 | ||
|
|
a77e3c3e7a | ||
|
|
f20aa192d8 | ||
|
|
1bed97c95e | ||
|
|
9a250e1e04 | ||
|
|
d2ef431f8c | ||
|
|
7eaa200d5f | ||
|
|
99bc287556 | ||
|
|
573c9d746c | ||
|
|
03b873d4dd | ||
|
|
1701f36942 | ||
|
|
9bd4433498 | ||
|
|
0717efe807 |
@@ -13,190 +13,193 @@ permissions:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build-windows-release:
|
build-windows-release:
|
||||||
name: Build Windows x64 Release
|
name: Build Windows x64 Release on Linux (MinGW + Qt + OpenCV)
|
||||||
# Windows runner 已注册标签:windows-latest、windows-2022、self-hosted;均为 host 模式。
|
runs-on: ubuntu-latest
|
||||||
runs-on: windows-2022
|
container: fedora:latest
|
||||||
|
|
||||||
env:
|
env:
|
||||||
BUILD_TYPE: Release
|
BUILD_TYPE: Release
|
||||||
MSYS2_ROOT: C:\msys64
|
PACKAGE_BASENAME: chengnan-windows-x64-mingw
|
||||||
MSYSTEM: UCRT64
|
|
||||||
CHERE_INVOKING: 1
|
|
||||||
PACKAGE_BASENAME: chengnan-windows-x64
|
|
||||||
PACKAGE_NAME: chengnan-windows-x64
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Prepare source
|
- name: Configure Fedora TUNA mirror
|
||||||
shell: powershell
|
|
||||||
run: |
|
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
|
set -euo pipefail
|
||||||
cd '$src'
|
sed -e 's|^metalink=|#metalink=|g' \
|
||||||
export PATH=/ucrt64/bin:/usr/bin:`$PATH
|
-e 's|^#baseurl=http://download.example/pub/fedora/linux|baseurl=https://mirrors.aliyun.com/fedora|g' \
|
||||||
cmake -S . -B build-windows -G Ninja -DCMAKE_BUILD_TYPE=Release
|
-i /etc/yum.repos.d/fedora*.repo
|
||||||
cmake --build build-windows --parallel `$(nproc)
|
if [ -f /etc/yum.repos.d/fedora-cisco-openh264.repo ]; then
|
||||||
rm -rf dist-windows
|
sed -i 's|^enabled=1|enabled=0|g' /etc/yum.repos.d/fedora-cisco-openh264.repo
|
||||||
mkdir -p dist-windows/chengnan
|
fi
|
||||||
cp build-windows/chengnan.exe dist-windows/chengnan/
|
dnf clean all
|
||||||
/ucrt64/bin/windeployqt6.exe --release --no-translations dist-windows/chengnan/chengnan.exe || /ucrt64/bin/windeployqt.exe --release --no-translations dist-windows/chengnan/chengnan.exe
|
dnf makecache --refresh -y
|
||||||
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
|
- name: Install cross build dependencies
|
||||||
shell: powershell
|
|
||||||
run: |
|
run: |
|
||||||
$ErrorActionPreference = 'Stop'
|
set -euo pipefail
|
||||||
$shortSha = $env:GITHUB_SHA.Substring(0, 10)
|
dnf install -y \
|
||||||
$version = if ($env:GITHUB_REF_TYPE -eq 'tag') { $env:GITHUB_REF_NAME } else { "build-$shortSha" }
|
git \
|
||||||
$zipName = "$env:PACKAGE_BASENAME-$version.zip"
|
curl \
|
||||||
$sourceDir = Join-Path $env:RUNNER_TEMP 'chengnan-work'
|
jq \
|
||||||
$dist = Join-Path $sourceDir 'dist-windows\chengnan'
|
zip \
|
||||||
if (-not (Test-Path "$dist\chengnan.exe")) { throw "Missing build output: $dist\chengnan.exe" }
|
unzip \
|
||||||
Push-Location (Split-Path $dist -Parent)
|
python3 \
|
||||||
if (Test-Path (Join-Path $sourceDir $zipName)) { Remove-Item -Force (Join-Path $sourceDir $zipName) }
|
nodejs \
|
||||||
Compress-Archive -Path 'chengnan\*' -DestinationPath (Join-Path $sourceDir $zipName) -Force
|
cmake \
|
||||||
Pop-Location
|
ninja-build \
|
||||||
$zipPath = Join-Path $sourceDir $zipName
|
mingw64-gcc-c++ \
|
||||||
$hash = (Get-FileHash $zipPath -Algorithm SHA256).Hash.ToLowerInvariant()
|
mingw64-qt6-qtbase \
|
||||||
"$hash $zipName" | Out-File -FilePath "$zipPath.sha256" -Encoding ascii
|
mingw64-qt6-qtimageformats \
|
||||||
Write-Host "Package: $zipPath"
|
mingw64-opencv
|
||||||
Write-Host "SHA256: $hash"
|
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Configure cross build
|
||||||
|
run: |
|
||||||
|
cmake -S . -B build-windows -G Ninja \
|
||||||
|
-DCMAKE_TOOLCHAIN_FILE=/usr/share/mingw/toolchain-mingw64.cmake \
|
||||||
|
-DCMAKE_BUILD_TYPE="$BUILD_TYPE" \
|
||||||
|
-DCMAKE_CXX_FLAGS="-isystem /usr/x86_64-w64-mingw32/sys-root/mingw/include/opencv4" \
|
||||||
|
-DOpenCV_DIR=/usr/x86_64-w64-mingw32/sys-root/mingw/lib/cmake/OpenCV
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: cmake --build build-windows --config "$BUILD_TYPE" --parallel
|
||||||
|
|
||||||
|
- name: Package Windows app
|
||||||
|
run: |
|
||||||
|
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
|
||||||
|
|
||||||
|
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/"
|
||||||
|
find "$root/bin" -maxdepth 1 -name "*opencv*" -exec cp -t "$dist/" {} +
|
||||||
|
install -m 0644 readme.md "$dist/readme.md"
|
||||||
|
|
||||||
|
cat > "$dist/README.txt" <<'EOF'
|
||||||
|
chengnan Windows x64 package
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
1. Extract the whole directory.
|
||||||
|
2. Double-click chengnan.exe to run.
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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
|
- name: Verify package
|
||||||
shell: powershell
|
|
||||||
run: |
|
run: |
|
||||||
$ErrorActionPreference = 'Stop'
|
set -euo pipefail
|
||||||
$shortSha = $env:GITHUB_SHA.Substring(0, 10)
|
test -s "artifacts/$PACKAGE"
|
||||||
$version = if ($env:GITHUB_REF_TYPE -eq 'tag') { $env:GITHUB_REF_NAME } else { "build-$shortSha" }
|
test -s "artifacts/$PACKAGE.sha256"
|
||||||
$zipName = "$env:PACKAGE_BASENAME-$version.zip"
|
unzip -l "artifacts/$PACKAGE" | grep -E 'chengnan/chengnan.exe' > /dev/null
|
||||||
$sourceDir = Join-Path $env:RUNNER_TEMP 'chengnan-work'
|
unzip -l "artifacts/$PACKAGE" | grep -E 'chengnan/platforms/qwindows.dll' > /dev/null
|
||||||
$zipPath = Join-Path $sourceDir $zipName
|
unzip -l "artifacts/$PACKAGE" | grep -E 'chengnan/.*opencv.*\.dll' > /dev/null
|
||||||
$shaPath = "$zipPath.sha256"
|
sha256sum -c "artifacts/$PACKAGE.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
|
- name: Upload package to repository release
|
||||||
shell: powershell
|
|
||||||
env:
|
env:
|
||||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
run: |
|
run: |
|
||||||
$ErrorActionPreference = 'Stop'
|
set -euo pipefail
|
||||||
$token = $env:RELEASE_TOKEN
|
token="${RELEASE_TOKEN:-${GITHUB_TOKEN:-}}"
|
||||||
if ([string]::IsNullOrWhiteSpace($token)) { $token = $env:GITHUB_TOKEN }
|
if [ -z "$token" ]; then
|
||||||
if ([string]::IsNullOrWhiteSpace($token)) { throw 'Missing release token. Configure RELEASE_TOKEN in repository secrets or ensure GITHUB_TOKEN is available.' }
|
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)
|
server_url="${GITHUB_SERVER_URL%/}"
|
||||||
$version = if ($env:GITHUB_REF_TYPE -eq 'tag') { $env:GITHUB_REF_NAME } else { "build-$shortSha" }
|
api_base="$server_url/api/v1/repos/$GITHUB_REPOSITORY"
|
||||||
$zipName = "$env:PACKAGE_BASENAME-$version.zip"
|
tag_name="$VERSION"
|
||||||
$sourceDir = Join-Path $env:RUNNER_TEMP 'chengnan-work'
|
if [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then
|
||||||
$zipPath = Join-Path $sourceDir $zipName
|
prerelease=false
|
||||||
$shaPath = "$zipPath.sha256"
|
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' }
|
release_payload=$(jq -n \
|
||||||
$repo = $env:GITHUB_REPOSITORY
|
--arg tag_name "$tag_name" \
|
||||||
$apiBase = "$serverUrl/api/v1/repos/$repo"
|
--arg target_commitish "$GITHUB_SHA" \
|
||||||
$tagName = $version
|
--arg name "$release_name" \
|
||||||
$releaseName = if ($env:GITHUB_REF_TYPE -eq 'tag') { $env:GITHUB_REF_NAME } else { "chengnan $shortSha" }
|
--arg body "Automated Windows x64 MinGW build from Linux Gitea Actions." \
|
||||||
$isPrerelease = if ($env:GITHUB_REF_TYPE -eq 'tag') { $false } else { $true }
|
--argjson prerelease "$prerelease" \
|
||||||
$headers = @{ Authorization = "token $token"; Accept = 'application/json' }
|
'{tag_name:$tag_name,target_commitish:$target_commitish,name:$name,body:$body,draft:false,prerelease:$prerelease}')
|
||||||
|
|
||||||
$releasePayload = @{
|
status=$(curl --silent --show-error --location \
|
||||||
tag_name = $tagName
|
--header "Authorization: token $token" \
|
||||||
target_commitish = $env:GITHUB_SHA
|
--header 'Content-Type: application/json' \
|
||||||
name = $releaseName
|
--write-out '%{http_code}' \
|
||||||
body = "Automated Windows x64 build from Gitea Actions.`n"
|
--output release.json \
|
||||||
draft = $false
|
--data "$release_payload" \
|
||||||
prerelease = $isPrerelease
|
"$api_base/releases")
|
||||||
} | ConvertTo-Json -Depth 5
|
|
||||||
|
|
||||||
try {
|
if [ "$status" != "200" ] && [ "$status" != "201" ]; then
|
||||||
$release = Invoke-RestMethod -Method Post -Uri "$apiBase/releases" -Headers $headers -ContentType 'application/json' -Body $releasePayload
|
curl --silent --show-error --location \
|
||||||
} catch {
|
--header "Authorization: token $token" \
|
||||||
$release = Invoke-RestMethod -Method Get -Uri "$apiBase/releases/tags/$tagName" -Headers $headers
|
--output release.json \
|
||||||
}
|
"$api_base/releases/tags/$tag_name"
|
||||||
|
fi
|
||||||
|
|
||||||
function Remove-ExistingAsset([string]$assetName) {
|
release_id=$(jq -r '.id' release.json)
|
||||||
$assets = Invoke-RestMethod -Method Get -Uri "$apiBase/releases/$($release.id)/assets" -Headers $headers
|
if [ -z "$release_id" ] || [ "$release_id" = "null" ]; then
|
||||||
foreach ($asset in @($assets)) {
|
echo 'Failed to resolve release id.' >&2
|
||||||
if ($asset.name -eq $assetName) {
|
cat release.json >&2
|
||||||
Invoke-RestMethod -Method Delete -Uri "$apiBase/releases/assets/$($asset.id)" -Headers $headers | Out-Null
|
exit 1
|
||||||
}
|
fi
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Upload-Asset([string]$path) {
|
upload_asset() {
|
||||||
$name = Split-Path $path -Leaf
|
local path="$1"
|
||||||
Remove-ExistingAsset $name
|
local name
|
||||||
$uploadUrl = "$apiBase/releases/$($release.id)/assets?name=$([uri]::EscapeDataString($name))"
|
name=$(basename "$path")
|
||||||
$responseFile = Join-Path $env:RUNNER_TEMP "gitea-upload-response.json"
|
curl --silent --show-error --location \
|
||||||
$curl = Join-Path $env:SystemRoot 'System32\curl.exe'
|
--header "Authorization: token $token" \
|
||||||
$status = & $curl --silent --show-error --location `
|
"$api_base/releases/$release_id/assets" > assets.json
|
||||||
--header "Authorization: token $token" `
|
jq -r --arg name "$name" '.[] | select(.name == $name) | .id' assets.json | while read -r asset_id; do
|
||||||
--form "attachment=@$path;filename=$name" `
|
[ -n "$asset_id" ] && curl --silent --show-error --location \
|
||||||
--write-out '%{http_code}' `
|
--request DELETE \
|
||||||
--output $responseFile `
|
--header "Authorization: token $token" \
|
||||||
$uploadUrl
|
"$api_base/releases/assets/$asset_id" >/dev/null
|
||||||
if ($status -ne '200' -and $status -ne '201') {
|
done
|
||||||
Write-Error "Upload release asset failed, HTTP ${status}: $name"
|
|
||||||
if (Test-Path $responseFile) { Get-Content $responseFile }
|
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
|
exit 1
|
||||||
}
|
fi
|
||||||
Write-Host "Uploaded release asset: $name"
|
echo "Uploaded release asset: $name"
|
||||||
}
|
}
|
||||||
|
|
||||||
Upload-Asset $zipPath
|
upload_asset "artifacts/$PACKAGE"
|
||||||
Upload-Asset $shaPath
|
upload_asset "artifacts/$PACKAGE.sha256"
|
||||||
Write-Host "Release assets uploaded to $serverUrl/$repo/releases/tag/$tagName"
|
echo "Release assets uploaded to $server_url/$GITHUB_REPOSITORY/releases/tag/$tag_name"
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ set(CMAKE_AUTOMOC ON)
|
|||||||
set(CMAKE_AUTOUIC OFF)
|
set(CMAKE_AUTOUIC OFF)
|
||||||
set(CMAKE_AUTORCC OFF)
|
set(CMAKE_AUTORCC OFF)
|
||||||
|
|
||||||
|
find_package(OpenCV REQUIRED COMPONENTS core imgproc imgcodecs)
|
||||||
|
|
||||||
find_package(Qt6 QUIET COMPONENTS Widgets)
|
find_package(Qt6 QUIET COMPONENTS Widgets)
|
||||||
if (Qt6_FOUND)
|
if (Qt6_FOUND)
|
||||||
qt_add_executable(chengnan
|
qt_add_executable(chengnan
|
||||||
@@ -15,7 +17,7 @@ if (Qt6_FOUND)
|
|||||||
MainWindow.h
|
MainWindow.h
|
||||||
MainWindow.cpp
|
MainWindow.cpp
|
||||||
)
|
)
|
||||||
target_link_libraries(chengnan PRIVATE Qt6::Widgets)
|
target_link_libraries(chengnan PRIVATE Qt6::Widgets ${OpenCV_LIBS})
|
||||||
else()
|
else()
|
||||||
find_package(Qt5 REQUIRED COMPONENTS Widgets)
|
find_package(Qt5 REQUIRED COMPONENTS Widgets)
|
||||||
add_executable(chengnan
|
add_executable(chengnan
|
||||||
@@ -23,9 +25,11 @@ else()
|
|||||||
MainWindow.h
|
MainWindow.h
|
||||||
MainWindow.cpp
|
MainWindow.cpp
|
||||||
)
|
)
|
||||||
target_link_libraries(chengnan PRIVATE Qt5::Widgets)
|
target_link_libraries(chengnan PRIVATE Qt5::Widgets ${OpenCV_LIBS})
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
target_include_directories(chengnan PRIVATE ${OpenCV_INCLUDE_DIRS})
|
||||||
|
|
||||||
target_compile_definitions(chengnan PRIVATE
|
target_compile_definitions(chengnan PRIVATE
|
||||||
CHENGNAN_APP_VERSION="${PROJECT_VERSION}"
|
CHENGNAN_APP_VERSION="${PROJECT_VERSION}"
|
||||||
)
|
)
|
||||||
|
|||||||
277
MainWindow.cpp
277
MainWindow.cpp
@@ -10,12 +10,119 @@
|
|||||||
#include <QMenuBar>
|
#include <QMenuBar>
|
||||||
#include <QMessageBox>
|
#include <QMessageBox>
|
||||||
#include <QMouseEvent>
|
#include <QMouseEvent>
|
||||||
|
#include <QScrollBar>
|
||||||
#include <QSlider>
|
#include <QSlider>
|
||||||
|
#include <QSplitter>
|
||||||
#include <QStatusBar>
|
#include <QStatusBar>
|
||||||
|
#include <QThread>
|
||||||
#include <QToolBar>
|
#include <QToolBar>
|
||||||
|
#include <QTransform>
|
||||||
|
|
||||||
|
#include <opencv2/imgproc.hpp>
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
|
#include <exception>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
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<uchar *>(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<int>(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<std::vector<cv::Point>> 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<double>(cv::countNonZero(edges)) / static_cast<double>(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)
|
ImageLabel::ImageLabel(QWidget *parent)
|
||||||
: QLabel(parent)
|
: QLabel(parent)
|
||||||
@@ -45,8 +152,8 @@ MainWindow::MainWindow(QWidget *parent)
|
|||||||
createCentralWidget();
|
createCentralWidget();
|
||||||
updateActions();
|
updateActions();
|
||||||
|
|
||||||
setWindowTitle(tr("chengnan 图片查看器"));
|
setWindowTitle(tr("chengnan 图片处理工具"));
|
||||||
resize(1100, 720);
|
resize(1200, 720);
|
||||||
statusBar()->showMessage(tr("就绪"));
|
statusBar()->showMessage(tr("就绪"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,6 +208,12 @@ void MainWindow::createActions()
|
|||||||
|
|
||||||
invertAction_ = new QAction(tr("反色"), this);
|
invertAction_ = new QAction(tr("反色"), this);
|
||||||
connect(invertAction_, &QAction::triggered, this, &MainWindow::invertColors);
|
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()
|
void MainWindow::createMenus()
|
||||||
@@ -126,6 +239,9 @@ void MainWindow::createMenus()
|
|||||||
processMenu->addSeparator();
|
processMenu->addSeparator();
|
||||||
processMenu->addAction(grayscaleAction_);
|
processMenu->addAction(grayscaleAction_);
|
||||||
processMenu->addAction(invertAction_);
|
processMenu->addAction(invertAction_);
|
||||||
|
processMenu->addSeparator();
|
||||||
|
processMenu->addAction(extractAction_);
|
||||||
|
processMenu->addAction(classifyAction_);
|
||||||
}
|
}
|
||||||
|
|
||||||
void MainWindow::createToolbar()
|
void MainWindow::createToolbar()
|
||||||
@@ -152,18 +268,35 @@ void MainWindow::createToolbar()
|
|||||||
toolbar->addAction(rotateRightAction_);
|
toolbar->addAction(rotateRightAction_);
|
||||||
toolbar->addAction(grayscaleAction_);
|
toolbar->addAction(grayscaleAction_);
|
||||||
toolbar->addAction(invertAction_);
|
toolbar->addAction(invertAction_);
|
||||||
|
toolbar->addAction(extractAction_);
|
||||||
|
toolbar->addAction(classifyAction_);
|
||||||
}
|
}
|
||||||
|
|
||||||
void MainWindow::createCentralWidget()
|
void MainWindow::createCentralWidget()
|
||||||
{
|
{
|
||||||
imageLabel_ = new ImageLabel(this);
|
originalLabel_ = new ImageLabel(this);
|
||||||
connect(imageLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow);
|
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);
|
originalScrollArea_ = new QScrollArea(this);
|
||||||
scrollArea_->setBackgroundRole(QPalette::Dark);
|
originalScrollArea_->setBackgroundRole(QPalette::Dark);
|
||||||
scrollArea_->setWidget(imageLabel_);
|
originalScrollArea_->setWidget(originalLabel_);
|
||||||
scrollArea_->setWidgetResizable(true);
|
originalScrollArea_->setWidgetResizable(true);
|
||||||
setCentralWidget(scrollArea_);
|
|
||||||
|
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()
|
void MainWindow::openImage()
|
||||||
@@ -236,7 +369,7 @@ void MainWindow::fitToWindow()
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const QSize viewportSize = scrollArea_->viewport()->size();
|
const QSize viewportSize = processedScrollArea_->viewport()->size();
|
||||||
const QSize imageSize = currentImage_.size();
|
const QSize imageSize = currentImage_.size();
|
||||||
if (imageSize.isEmpty()) {
|
if (imageSize.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
@@ -290,20 +423,35 @@ void MainWindow::flipVertical()
|
|||||||
|
|
||||||
void MainWindow::grayscale()
|
void MainWindow::grayscale()
|
||||||
{
|
{
|
||||||
if (!ensureImageLoaded(tr("灰度化"))) {
|
processImageInThread(tr("灰度化"), tr("灰度化完成,可保存结果"), [](QImage image) {
|
||||||
return;
|
cv::Mat rgba = qImageToMat(image);
|
||||||
}
|
cv::Mat gray;
|
||||||
applyTransformedImage(currentImage_.convertToFormat(QImage::Format_Grayscale8));
|
cv::cvtColor(rgba, gray, cv::COLOR_RGBA2GRAY);
|
||||||
|
return matToQImage(gray);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void MainWindow::invertColors()
|
void MainWindow::invertColors()
|
||||||
{
|
{
|
||||||
if (!ensureImageLoaded(tr("反色"))) {
|
processImageInThread(tr("反色"), tr("反色完成,可保存结果"), [](QImage image) {
|
||||||
return;
|
QImage result = image.convertToFormat(QImage::Format_ARGB32);
|
||||||
}
|
result.invertPixels(QImage::InvertRgb);
|
||||||
QImage image = currentImage_.convertToFormat(QImage::Format_ARGB32);
|
return result;
|
||||||
image.invertPixels(QImage::InvertRgb);
|
});
|
||||||
applyTransformedImage(image);
|
}
|
||||||
|
|
||||||
|
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)
|
void MainWindow::updateZoomFromSlider(int value)
|
||||||
@@ -317,43 +465,55 @@ void MainWindow::updateZoomFromSlider(int value)
|
|||||||
|
|
||||||
void MainWindow::setImage(const QImage &image, const QString &path)
|
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;
|
currentPath_ = path;
|
||||||
setZoomFactor(1.0);
|
setZoomFactor(1.0);
|
||||||
updateActions();
|
updateActions();
|
||||||
|
|
||||||
const QFileInfo info(path);
|
const QFileInfo info(path);
|
||||||
setWindowTitle(path.isEmpty()
|
setWindowTitle(path.isEmpty()
|
||||||
? tr("chengnan 图片查看器")
|
? tr("chengnan 图片处理工具")
|
||||||
: tr("%1 - chengnan 图片查看器").arg(info.fileName()));
|
: tr("%1 - chengnan 图片处理工具").arg(info.fileName()));
|
||||||
statusBar()->showMessage(tr("已加载:%1 × %2").arg(currentImage_.width()).arg(currentImage_.height()), 5000);
|
statusBar()->showMessage(tr("已加载:%1 × %2").arg(currentImage_.width()).arg(currentImage_.height()), 5000);
|
||||||
}
|
}
|
||||||
|
|
||||||
void MainWindow::updateImageView()
|
void MainWindow::updateImageView()
|
||||||
{
|
{
|
||||||
if (currentImage_.isNull()) {
|
if (currentImage_.isNull()) {
|
||||||
imageLabel_->setPixmap(QPixmap());
|
originalLabel_->setPixmap(QPixmap());
|
||||||
imageLabel_->setText(tr("打开一张图片开始查看"));
|
processedLabel_->setPixmap(QPixmap());
|
||||||
|
originalLabel_->setText(tr("处理前图像"));
|
||||||
|
processedLabel_->setText(tr("处理后图像"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const QSize scaledSize = currentImage_.size() * zoomFactor_;
|
updateSingleView(originalLabel_, originalImage_);
|
||||||
const QPixmap pixmap = QPixmap::fromImage(currentImage_).scaled(
|
updateSingleView(processedLabel_, currentImage_);
|
||||||
|
|
||||||
|
const int sliderValue = static_cast<int>(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<int>(std::round(image.width() * zoomFactor_))),
|
||||||
|
std::max(1, static_cast<int>(std::round(image.height() * zoomFactor_))));
|
||||||
|
const QPixmap pixmap = QPixmap::fromImage(image).scaled(
|
||||||
scaledSize,
|
scaledSize,
|
||||||
Qt::KeepAspectRatio,
|
Qt::KeepAspectRatio,
|
||||||
Qt::SmoothTransformation);
|
Qt::SmoothTransformation);
|
||||||
|
|
||||||
imageLabel_->setText(QString());
|
label->setText(QString());
|
||||||
imageLabel_->setPixmap(pixmap);
|
label->setPixmap(pixmap);
|
||||||
imageLabel_->resize(pixmap.size());
|
label->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)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void MainWindow::setZoomFactor(double factor)
|
void MainWindow::setZoomFactor(double factor)
|
||||||
@@ -362,12 +522,45 @@ void MainWindow::setZoomFactor(double factor)
|
|||||||
updateImageView();
|
updateImageView();
|
||||||
}
|
}
|
||||||
|
|
||||||
void MainWindow::applyTransformedImage(const QImage &image)
|
void MainWindow::applyTransformedImage(const QImage &image, const QString &message)
|
||||||
{
|
{
|
||||||
currentImage_ = image.convertToFormat(QImage::Format_ARGB32);
|
currentImage_ = image.convertToFormat(QImage::Format_ARGB32);
|
||||||
updateImageView();
|
updateImageView();
|
||||||
updateActions();
|
updateActions();
|
||||||
statusBar()->showMessage(tr("处理完成,可保存结果"), 3000);
|
statusBar()->showMessage(message.isEmpty() ? tr("处理完成,可保存结果") : message, 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MainWindow::processImageInThread(const QString &actionName,
|
||||||
|
const QString &doneMessage,
|
||||||
|
const std::function<QImage(QImage)> &processor)
|
||||||
|
{
|
||||||
|
if (!ensureImageLoaded(actionName)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const QImage input = currentImage_;
|
||||||
|
auto result = std::make_shared<QImage>();
|
||||||
|
auto error = std::make_shared<QString>();
|
||||||
|
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()
|
void MainWindow::updateActions()
|
||||||
@@ -385,6 +578,8 @@ void MainWindow::updateActions()
|
|||||||
flipVerticalAction_->setEnabled(hasImage);
|
flipVerticalAction_->setEnabled(hasImage);
|
||||||
grayscaleAction_->setEnabled(hasImage);
|
grayscaleAction_->setEnabled(hasImage);
|
||||||
invertAction_->setEnabled(hasImage);
|
invertAction_->setEnabled(hasImage);
|
||||||
|
extractAction_->setEnabled(hasImage);
|
||||||
|
classifyAction_->setEnabled(hasImage);
|
||||||
zoomSlider_->setEnabled(hasImage);
|
zoomSlider_->setEnabled(hasImage);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -407,7 +602,7 @@ bool MainWindow::writeImageToPath(const QString &path)
|
|||||||
}
|
}
|
||||||
|
|
||||||
currentPath_ = 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);
|
statusBar()->showMessage(tr("已保存:%1").arg(path), 5000);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
16
MainWindow.h
16
MainWindow.h
@@ -7,6 +7,7 @@
|
|||||||
#include <QPixmap>
|
#include <QPixmap>
|
||||||
#include <QScrollArea>
|
#include <QScrollArea>
|
||||||
#include <QString>
|
#include <QString>
|
||||||
|
#include <functional>
|
||||||
|
|
||||||
class QAction;
|
class QAction;
|
||||||
class QMenu;
|
class QMenu;
|
||||||
@@ -48,6 +49,8 @@ private Q_SLOTS:
|
|||||||
void flipVertical();
|
void flipVertical();
|
||||||
void grayscale();
|
void grayscale();
|
||||||
void invertColors();
|
void invertColors();
|
||||||
|
void extractObjects();
|
||||||
|
void classifyImage();
|
||||||
void updateZoomFromSlider(int value);
|
void updateZoomFromSlider(int value);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -57,16 +60,21 @@ private:
|
|||||||
void createCentralWidget();
|
void createCentralWidget();
|
||||||
void setImage(const QImage &image, const QString &path = QString());
|
void setImage(const QImage &image, const QString &path = QString());
|
||||||
void updateImageView();
|
void updateImageView();
|
||||||
|
void updateSingleView(ImageLabel *label, const QImage &image);
|
||||||
void setZoomFactor(double factor);
|
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<QImage(QImage)> &processor);
|
||||||
void updateActions();
|
void updateActions();
|
||||||
bool ensureImageLoaded(const QString &actionName) const;
|
bool ensureImageLoaded(const QString &actionName) const;
|
||||||
bool writeImageToPath(const QString &path);
|
bool writeImageToPath(const QString &path);
|
||||||
|
|
||||||
ImageLabel *imageLabel_ = nullptr;
|
ImageLabel *originalLabel_ = nullptr;
|
||||||
QScrollArea *scrollArea_ = nullptr;
|
ImageLabel *processedLabel_ = nullptr;
|
||||||
|
QScrollArea *originalScrollArea_ = nullptr;
|
||||||
|
QScrollArea *processedScrollArea_ = nullptr;
|
||||||
QSlider *zoomSlider_ = nullptr;
|
QSlider *zoomSlider_ = nullptr;
|
||||||
|
|
||||||
|
QImage originalImage_;
|
||||||
QImage currentImage_;
|
QImage currentImage_;
|
||||||
QString currentPath_;
|
QString currentPath_;
|
||||||
double zoomFactor_ = 1.0;
|
double zoomFactor_ = 1.0;
|
||||||
@@ -85,6 +93,8 @@ private:
|
|||||||
QAction *flipVerticalAction_ = nullptr;
|
QAction *flipVerticalAction_ = nullptr;
|
||||||
QAction *grayscaleAction_ = nullptr;
|
QAction *grayscaleAction_ = nullptr;
|
||||||
QAction *invertAction_ = nullptr;
|
QAction *invertAction_ = nullptr;
|
||||||
|
QAction *extractAction_ = nullptr;
|
||||||
|
QAction *classifyAction_ = nullptr;
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // MAINWINDOW_H
|
#endif // MAINWINDOW_H
|
||||||
|
|||||||
@@ -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"
|
|
||||||
117
readme.md
117
readme.md
@@ -2,34 +2,52 @@
|
|||||||
|
|
||||||
项目链接:<https://git.luochen570.cn/luochen570/chengnan>
|
项目链接:<https://git.luochen570.cn/luochen570/chengnan>
|
||||||
|
|
||||||
`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、JPEG、BMP、GIF、WebP 等 Qt 支持的格式
|
||||||
- 保存当前图片
|
- 保存当前处理后图片
|
||||||
- 另存为 PNG / JPG / BMP 等格式
|
- 另存为 PNG / JPG / BMP 等格式
|
||||||
- 图片显示:使用 Qt Widgets,不使用 OpenCV 窗口
|
- 处理前 / 处理后双栏对比显示
|
||||||
- 缩放:工具栏滑块、放大、缩小、原始大小
|
- 缩放:工具栏滑块、放大、缩小、原始大小
|
||||||
|
- 平移:放大后使用滚动条移动查看区域
|
||||||
- 双击图片适配窗口
|
- 双击图片适配窗口
|
||||||
- 旋转:左旋 90°、右旋 90°
|
- 旋转:左旋 90°、右旋 90°
|
||||||
- 翻转:水平翻转、垂直翻转
|
- 翻转:水平翻转、垂直翻转
|
||||||
- 简单处理:灰度化、反色
|
- OpenCV 图片处理:灰度化、目标提取、简单分类
|
||||||
|
- 其它处理:反色
|
||||||
|
|
||||||
## 文件结构
|
## 文件结构
|
||||||
|
|
||||||
```text
|
```text
|
||||||
chengnan/
|
chengnan/
|
||||||
|
├── .gitea/workflows/build-windows-release.yml
|
||||||
├── CMakeLists.txt
|
├── CMakeLists.txt
|
||||||
├── MainWindow.cpp
|
├── MainWindow.cpp
|
||||||
├── MainWindow.h
|
├── MainWindow.h
|
||||||
├── build-windows.ps1
|
|
||||||
├── main.cpp
|
├── main.cpp
|
||||||
└── readme.md
|
└── readme.md
|
||||||
```
|
```
|
||||||
|
|
||||||
|
除工作流和 `readme.md` 外,工程根目录只保留 `CMakeLists.txt`、`main.cpp`、`MainWindow.h`、`MainWindow.cpp` 四个文件。
|
||||||
|
|
||||||
## Windows 编译需要的工具
|
## Windows 编译需要的工具
|
||||||
|
|
||||||
推荐环境:Windows 10 / Windows 11 x64。
|
推荐环境:Windows 10 / Windows 11 x64。
|
||||||
@@ -47,18 +65,16 @@ chengnan/
|
|||||||
3. **Qt 6 或 Qt 5,包含 Widgets 模块**
|
3. **Qt 6 或 Qt 5,包含 Widgets 模块**
|
||||||
- 下载:<https://www.qt.io/download-qt-installer-oss>
|
- 下载:<https://www.qt.io/download-qt-installer-oss>
|
||||||
- 推荐安装 Qt 6.x 的 MSVC 64-bit 套件,例如 `msvc2019_64` 或 `msvc2022_64`。
|
- 推荐安装 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 预编译包**
|
||||||
|
- 下载:<https://opencv.org/releases/>
|
||||||
|
- 解压后 CMake 需要能找到 OpenCV 的 `build` 目录,例如 `C:\opencv\build`。
|
||||||
|
|
||||||
|
5. **Visual Studio 2022 Build Tools 或 Visual Studio 2022**
|
||||||
- 下载:<https://visualstudio.microsoft.com/zh-hans/downloads/>
|
- 下载:<https://visualstudio.microsoft.com/zh-hans/downloads/>
|
||||||
- 需要安装组件:`使用 C++ 的桌面开发`。
|
- 需要安装组件:`使用 C++ 的桌面开发`。
|
||||||
- 提供 MSVC 编译器和 Windows SDK。
|
- 提供 MSVC 编译器和 Windows SDK。
|
||||||
|
|
||||||
可选工具:
|
|
||||||
|
|
||||||
- **Ninja**:<https://github.com/ninja-build/ninja/releases>
|
|
||||||
- 如果使用 Ninja,可以把 `build-windows.ps1` 的 `-Generator` 参数改成 `Ninja`。
|
|
||||||
|
|
||||||
## 获取源码
|
## 获取源码
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
@@ -66,63 +82,43 @@ git clone https://git.luochen570.cn/luochen570/chengnan.git
|
|||||||
cd chengnan
|
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
|
```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
|
cmake --build build-windows --config Release
|
||||||
```
|
```
|
||||||
|
|
||||||
打包 Qt 运行库:
|
打包 Qt 运行库:
|
||||||
|
|
||||||
```powershell
|
```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
|
### 找不到 Qt
|
||||||
|
|
||||||
确认 `-QtPrefix` 指向 Qt 套件目录,而不是 Qt 根目录。例如应使用:
|
确认 CMake 的 `CMAKE_PREFIX_PATH` 包含 Qt 套件目录,而不是 Qt 根目录。例如应使用:
|
||||||
|
|
||||||
```text
|
```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
|
C:\Qt
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### 找不到 OpenCV
|
||||||
|
|
||||||
|
确认 CMake 的 `CMAKE_PREFIX_PATH` 包含 OpenCV 的 `build` 目录。例如:
|
||||||
|
|
||||||
|
```text
|
||||||
|
C:\opencv\build
|
||||||
|
```
|
||||||
|
|
||||||
|
该目录下通常能找到 `OpenCVConfig.cmake`。
|
||||||
|
|
||||||
### 找不到 MSVC 编译器
|
### 找不到 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 复制到其它电脑无法运行
|
### exe 复制到其它电脑无法运行
|
||||||
|
|
||||||
请运行 `build-windows.ps1`,并整体复制 `dist-windows\chengnan` 文件夹,不要只复制单个 `chengnan.exe`。
|
不要只复制单个 `chengnan.exe`。需要同时复制 Qt / OpenCV DLL 和 Qt 插件目录,或直接使用 Gitea Actions 发布的 zip 附件。
|
||||||
|
|
||||||
## 开发说明
|
## 开发说明
|
||||||
|
|
||||||
- `main.cpp`:应用入口,创建并显示主窗口
|
- `main.cpp`:应用入口,创建并显示主窗口
|
||||||
- `MainWindow.h`:主窗口和图片标签类声明
|
- `MainWindow.h`:主窗口和图片标签类声明
|
||||||
- `MainWindow.cpp`:菜单、工具栏、图片显示和处理逻辑
|
- `MainWindow.cpp`:菜单、工具栏、图片显示、OpenCV 图像处理和 Qt 线程逻辑
|
||||||
- `CMakeLists.txt`:Qt Widgets CMake 构建配置
|
- `CMakeLists.txt`:Qt Widgets + OpenCV CMake 构建配置
|
||||||
- `build-windows.ps1`:Windows 一键构建与打包脚本
|
|
||||||
- `readme.md`:项目说明文档
|
- `readme.md`:项目说明文档
|
||||||
|
|||||||
Reference in New Issue
Block a user