Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
804a5db77d | ||
|
|
4e1f73bab7 | ||
|
|
57c053c77a | ||
|
|
4102ff3b74 | ||
|
|
7e7c9f1d74 | ||
|
|
c658fa4265 |
@@ -1,202 +0,0 @@
|
||||
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
@@ -0,0 +1,14 @@
|
||||
build/
|
||||
build-windows/
|
||||
build-wsl-windows/
|
||||
cmake-build-*/
|
||||
.qt/
|
||||
.qtc/
|
||||
CMakeUserPresets.json
|
||||
*.user
|
||||
*.suo
|
||||
*.vcxproj*
|
||||
*.sln
|
||||
*.exe
|
||||
*.dll
|
||||
*.pdb
|
||||
+17
-26
@@ -1,39 +1,30 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
project(chengnan VERSION 1.0.0 LANGUAGES CXX)
|
||||
project(QtOpenCVImageTool LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_AUTOMOC ON)
|
||||
set(CMAKE_AUTOUIC OFF)
|
||||
set(CMAKE_AUTORCC OFF)
|
||||
set(CMAKE_AUTORCC ON)
|
||||
set(CMAKE_AUTOUIC ON)
|
||||
|
||||
find_package(Qt6 QUIET COMPONENTS Widgets)
|
||||
if (Qt6_FOUND)
|
||||
qt_add_executable(chengnan
|
||||
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(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()
|
||||
target_link_libraries(QtOpenCVImageTool PRIVATE
|
||||
Qt${QT_VERSION_MAJOR}::Widgets
|
||||
${OpenCV_LIBS}
|
||||
)
|
||||
|
||||
install(TARGETS chengnan RUNTIME DESTINATION bin)
|
||||
target_include_directories(QtOpenCVImageTool PRIVATE ${OpenCV_INCLUDE_DIRS})
|
||||
|
||||
if(QT_VERSION_MAJOR EQUAL 6)
|
||||
qt_finalize_executable(QtOpenCVImageTool)
|
||||
endif()
|
||||
|
||||
+331
-311
@@ -1,413 +1,433 @@
|
||||
#include "MainWindow.h"
|
||||
|
||||
#include <QAction>
|
||||
#include <QApplication>
|
||||
#include <QCheckBox>
|
||||
#include <QFileDialog>
|
||||
#include <QFileInfo>
|
||||
#include <QImageReader>
|
||||
#include <QImageWriter>
|
||||
#include <QKeySequence>
|
||||
#include <QMenuBar>
|
||||
#include <QGroupBox>
|
||||
#include <QHBoxLayout>
|
||||
#include <QImage>
|
||||
#include <QLabel>
|
||||
#include <QMessageBox>
|
||||
#include <QMouseEvent>
|
||||
#include <QPushButton>
|
||||
#include <QPixmap>
|
||||
#include <QScrollArea>
|
||||
#include <QSlider>
|
||||
#include <QStatusBar>
|
||||
#include <QToolBar>
|
||||
#include <QThread>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
ImageLabel::ImageLabel(QWidget *parent)
|
||||
: QLabel(parent)
|
||||
namespace
|
||||
{
|
||||
setAlignment(Qt::AlignCenter);
|
||||
setBackgroundRole(QPalette::Base);
|
||||
setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
|
||||
setScaledContents(false);
|
||||
setMinimumSize(320, 240);
|
||||
setText(tr("打开一张图片开始查看"));
|
||||
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();
|
||||
}
|
||||
|
||||
void ImageLabel::mouseDoubleClickEvent(QMouseEvent *event)
|
||||
cv::Mat rotateWithBounds(const cv::Mat &image, double angle)
|
||||
{
|
||||
if (event->button() == Qt::LeftButton) {
|
||||
Q_EMIT doubleClicked();
|
||||
if (image.empty() || std::abs(angle) < 0.01) {
|
||||
return image.clone();
|
||||
}
|
||||
QLabel::mouseDoubleClickEvent(event);
|
||||
|
||||
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 ¶ms)
|
||||
{
|
||||
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);
|
||||
};
|
||||
}
|
||||
|
||||
MainWindow::MainWindow(QWidget *parent)
|
||||
: QMainWindow(parent)
|
||||
{
|
||||
createActions();
|
||||
createMenus();
|
||||
createToolbar();
|
||||
createCentralWidget();
|
||||
updateActions();
|
||||
qRegisterMetaType<cv::Mat>("cv::Mat");
|
||||
qRegisterMetaType<ProcessParams>("ProcessParams");
|
||||
|
||||
setWindowTitle(tr("chengnan 图片查看器"));
|
||||
resize(1100, 720);
|
||||
statusBar()->showMessage(tr("就绪"));
|
||||
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();
|
||||
}
|
||||
|
||||
void MainWindow::createActions()
|
||||
MainWindow::~MainWindow()
|
||||
{
|
||||
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);
|
||||
if (workerThread) {
|
||||
workerThread->quit();
|
||||
workerThread->wait();
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::createMenus()
|
||||
void MainWindow::buildUi()
|
||||
{
|
||||
QMenu *fileMenu = menuBar()->addMenu(tr("文件(&F)"));
|
||||
fileMenu->addAction(openAction_);
|
||||
fileMenu->addAction(saveAction_);
|
||||
fileMenu->addAction(saveAsAction_);
|
||||
fileMenu->addSeparator();
|
||||
fileMenu->addAction(exitAction_);
|
||||
setWindowTitle(QStringLiteral("Qt + OpenCV 图像显示与处理"));
|
||||
|
||||
QMenu *viewMenu = menuBar()->addMenu(tr("查看(&V)"));
|
||||
viewMenu->addAction(zoomInAction_);
|
||||
viewMenu->addAction(zoomOutAction_);
|
||||
viewMenu->addAction(fitAction_);
|
||||
viewMenu->addAction(resetAction_);
|
||||
auto *central = new QWidget(this);
|
||||
auto *rootLayout = new QVBoxLayout(central);
|
||||
|
||||
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 *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);
|
||||
|
||||
void MainWindow::createToolbar()
|
||||
{
|
||||
QToolBar *toolbar = addToolBar(tr("主工具栏"));
|
||||
toolbar->setMovable(false);
|
||||
toolbar->addAction(openAction_);
|
||||
toolbar->addAction(saveAction_);
|
||||
toolbar->addSeparator();
|
||||
toolbar->addAction(zoomOutAction_);
|
||||
auto *controlBox = new QGroupBox(QStringLiteral("图像处理"));
|
||||
auto *controlLayout = new QHBoxLayout(controlBox);
|
||||
|
||||
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_);
|
||||
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("图像分类"));
|
||||
|
||||
toolbar->addAction(zoomInAction_);
|
||||
toolbar->addAction(fitAction_);
|
||||
toolbar->addSeparator();
|
||||
toolbar->addAction(rotateLeftAction_);
|
||||
toolbar->addAction(rotateRightAction_);
|
||||
toolbar->addAction(grayscaleAction_);
|
||||
toolbar->addAction(invertAction_);
|
||||
}
|
||||
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);
|
||||
};
|
||||
|
||||
void MainWindow::createCentralWidget()
|
||||
{
|
||||
imageLabel_ = new ImageLabel(this);
|
||||
connect(imageLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow);
|
||||
addSlider(QStringLiteral("缩放"), scaleSlider);
|
||||
addSlider(QStringLiteral("旋转"), rotateSlider);
|
||||
addSlider(QStringLiteral("水平平移"), translateXSlider);
|
||||
addSlider(QStringLiteral("垂直平移"), translateYSlider);
|
||||
controlLayout->addWidget(extractCheckBox);
|
||||
controlLayout->addWidget(classifyCheckBox);
|
||||
|
||||
scrollArea_ = new QScrollArea(this);
|
||||
scrollArea_->setBackgroundRole(QPalette::Dark);
|
||||
scrollArea_->setWidget(imageLabel_);
|
||||
scrollArea_->setWidgetResizable(true);
|
||||
setCentralWidget(scrollArea_);
|
||||
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);
|
||||
}
|
||||
|
||||
void MainWindow::openImage()
|
||||
{
|
||||
const QString fileName = QFileDialog::getOpenFileName(
|
||||
this,
|
||||
tr("打开图片"),
|
||||
QStringLiteral("打开图片"),
|
||||
QString(),
|
||||
tr("图片文件 (*.png *.jpg *.jpeg *.bmp *.gif *.webp);;所有文件 (*.*)"));
|
||||
QStringLiteral("Images (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)"));
|
||||
|
||||
if (fileName.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
QImageReader reader(fileName);
|
||||
reader.setAutoTransform(true);
|
||||
const QImage image = reader.read();
|
||||
if (image.isNull()) {
|
||||
QMessageBox::warning(this, tr("打开失败"), tr("无法读取图片:%1").arg(reader.errorString()));
|
||||
originalImage = cv::imread(fileName.toLocal8Bit().constData(), cv::IMREAD_COLOR);
|
||||
if (originalImage.empty()) {
|
||||
QMessageBox::warning(this, QStringLiteral("打开失败"), QStringLiteral("无法读取该图片文件。"));
|
||||
return;
|
||||
}
|
||||
|
||||
setImage(image, fileName);
|
||||
savePath.clear();
|
||||
updateOriginalView();
|
||||
scheduleProcessing();
|
||||
statusLabel->setText(QStringLiteral("已打开:%1").arg(QFileInfo(fileName).fileName()));
|
||||
}
|
||||
|
||||
void MainWindow::saveImage()
|
||||
{
|
||||
if (!ensureImageLoaded(tr("保存"))) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentPath_.isEmpty()) {
|
||||
if (savePath.isEmpty()) {
|
||||
saveImageAs();
|
||||
return;
|
||||
}
|
||||
|
||||
writeImageToPath(currentPath_);
|
||||
if (writeResultToFile(savePath)) {
|
||||
statusLabel->setText(QStringLiteral("已保存:%1").arg(QFileInfo(savePath).fileName()));
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::saveImageAs()
|
||||
{
|
||||
if (!ensureImageLoaded(tr("另存为"))) {
|
||||
if (resultImage.empty()) {
|
||||
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("请先打开并处理图片。"));
|
||||
return;
|
||||
}
|
||||
|
||||
const QString fileName = QFileDialog::getSaveFileName(
|
||||
this,
|
||||
tr("另存为"),
|
||||
currentPath_.isEmpty() ? QStringLiteral("chengnan.png") : currentPath_,
|
||||
tr("PNG 图片 (*.png);;JPEG 图片 (*.jpg *.jpeg);;BMP 图片 (*.bmp);;所有文件 (*.*)"));
|
||||
QStringLiteral("另存图片"),
|
||||
QStringLiteral("processed.png"),
|
||||
QStringLiteral("PNG (*.png);;JPEG (*.jpg *.jpeg);;BMP (*.bmp);;TIFF (*.tif *.tiff)"));
|
||||
|
||||
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("适配窗口"))) {
|
||||
if (fileName.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const QSize viewportSize = scrollArea_->viewport()->size();
|
||||
const QSize imageSize = currentImage_.size();
|
||||
if (imageSize.isEmpty()) {
|
||||
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()) {
|
||||
return;
|
||||
}
|
||||
|
||||
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));
|
||||
emit processRequested(originalImage.clone(), currentParams());
|
||||
}
|
||||
|
||||
void MainWindow::resetView()
|
||||
void MainWindow::onProcessed(const cv::Mat &image, const QString &classText)
|
||||
{
|
||||
setZoomFactor(1.0);
|
||||
resultImage = image.clone();
|
||||
updateResultView();
|
||||
statusLabel->setText(classText);
|
||||
}
|
||||
|
||||
void MainWindow::rotateLeft()
|
||||
void MainWindow::updateOriginalView()
|
||||
{
|
||||
if (!ensureImageLoaded(tr("旋转"))) {
|
||||
return;
|
||||
}
|
||||
QTransform transform;
|
||||
transform.rotate(-90);
|
||||
applyTransformedImage(currentImage_.transformed(transform, Qt::SmoothTransformation));
|
||||
setImageOnLabel(originalLabel, originalImage);
|
||||
}
|
||||
|
||||
void MainWindow::rotateRight()
|
||||
void MainWindow::updateResultView()
|
||||
{
|
||||
if (!ensureImageLoaded(tr("旋转"))) {
|
||||
return;
|
||||
}
|
||||
QTransform transform;
|
||||
transform.rotate(90);
|
||||
applyTransformedImage(currentImage_.transformed(transform, Qt::SmoothTransformation));
|
||||
setImageOnLabel(resultLabel, resultImage);
|
||||
}
|
||||
|
||||
void MainWindow::flipHorizontal()
|
||||
void MainWindow::setImageOnLabel(QLabel *label, const cv::Mat &mat)
|
||||
{
|
||||
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("打开一张图片开始查看"));
|
||||
const QImage image = matToQImage(mat);
|
||||
if (image.isNull()) {
|
||||
label->setText(QStringLiteral("无图像"));
|
||||
return;
|
||||
}
|
||||
|
||||
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)));
|
||||
label->setPixmap(QPixmap::fromImage(image).scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
|
||||
}
|
||||
|
||||
void MainWindow::setZoomFactor(double factor)
|
||||
ProcessParams MainWindow::currentParams() const
|
||||
{
|
||||
zoomFactor_ = std::clamp(factor, 0.10, 4.00);
|
||||
updateImageView();
|
||||
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;
|
||||
}
|
||||
|
||||
void MainWindow::applyTransformedImage(const QImage &image)
|
||||
bool MainWindow::writeResultToFile(const QString &fileName)
|
||||
{
|
||||
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 (resultImage.empty()) {
|
||||
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("没有可保存的处理结果。"));
|
||||
return false;
|
||||
}
|
||||
|
||||
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()));
|
||||
if (!cv::imwrite(fileName.toLocal8Bit().constData(), resultImage)) {
|
||||
QMessageBox::warning(this, QStringLiteral("保存失败"), QStringLiteral("无法写入该图片文件。"));
|
||||
return false;
|
||||
}
|
||||
|
||||
currentPath_ = path;
|
||||
setWindowTitle(tr("%1 - chengnan 图片查看器").arg(QFileInfo(path).fileName()));
|
||||
statusBar()->showMessage(tr("已保存:%1").arg(path), 5000);
|
||||
return true;
|
||||
}
|
||||
|
||||
#include "MainWindow.moc"
|
||||
|
||||
+49
-63
@@ -1,90 +1,76 @@
|
||||
#ifndef MAINWINDOW_H
|
||||
#define MAINWINDOW_H
|
||||
|
||||
#include <QImage>
|
||||
#include <QLabel>
|
||||
#include <QMainWindow>
|
||||
#include <QPixmap>
|
||||
#include <QScrollArea>
|
||||
#include <QString>
|
||||
#include <QMetaType>
|
||||
|
||||
class QAction;
|
||||
class QMenu;
|
||||
#include <opencv2/opencv.hpp>
|
||||
|
||||
class QLabel;
|
||||
class QPushButton;
|
||||
class QSlider;
|
||||
class QCheckBox;
|
||||
class QThread;
|
||||
|
||||
class ImageLabel final : public QLabel
|
||||
struct ProcessParams
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit ImageLabel(QWidget *parent = nullptr);
|
||||
|
||||
Q_SIGNALS:
|
||||
void doubleClicked();
|
||||
|
||||
protected:
|
||||
void mouseDoubleClickEvent(QMouseEvent *event) override;
|
||||
double scale = 1.0;
|
||||
int translateX = 0;
|
||||
int translateY = 0;
|
||||
double angle = 0.0;
|
||||
bool extractTarget = false;
|
||||
bool classifyImage = false;
|
||||
};
|
||||
|
||||
class MainWindow final : public QMainWindow
|
||||
Q_DECLARE_METATYPE(cv::Mat)
|
||||
Q_DECLARE_METATYPE(ProcessParams)
|
||||
|
||||
class MainWindow : public QMainWindow
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit MainWindow(QWidget *parent = nullptr);
|
||||
~MainWindow() override;
|
||||
|
||||
private Q_SLOTS:
|
||||
signals:
|
||||
void processRequested(const cv::Mat &image, const ProcessParams ¶ms);
|
||||
|
||||
private slots:
|
||||
void openImage();
|
||||
void saveImage();
|
||||
void saveImageAs();
|
||||
void zoomIn();
|
||||
void zoomOut();
|
||||
void fitToWindow();
|
||||
void resetView();
|
||||
void rotateLeft();
|
||||
void rotateRight();
|
||||
void flipHorizontal();
|
||||
void flipVertical();
|
||||
void grayscale();
|
||||
void invertColors();
|
||||
void updateZoomFromSlider(int value);
|
||||
void resetParams();
|
||||
void scheduleProcessing();
|
||||
void onProcessed(const cv::Mat &image, const QString &classText);
|
||||
|
||||
private:
|
||||
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);
|
||||
void buildUi();
|
||||
void updateOriginalView();
|
||||
void updateResultView();
|
||||
void setImageOnLabel(QLabel *label, const cv::Mat &mat);
|
||||
ProcessParams currentParams() const;
|
||||
bool writeResultToFile(const QString &fileName);
|
||||
|
||||
ImageLabel *imageLabel_ = nullptr;
|
||||
QScrollArea *scrollArea_ = nullptr;
|
||||
QSlider *zoomSlider_ = nullptr;
|
||||
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;
|
||||
|
||||
QImage currentImage_;
|
||||
QString currentPath_;
|
||||
double zoomFactor_ = 1.0;
|
||||
cv::Mat originalImage;
|
||||
cv::Mat resultImage;
|
||||
QString savePath;
|
||||
|
||||
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;
|
||||
QThread *workerThread = nullptr;
|
||||
};
|
||||
|
||||
#endif // MAINWINDOW_H
|
||||
#endif
|
||||
|
||||
Binary file not shown.
@@ -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"
|
||||
@@ -0,0 +1,46 @@
|
||||
@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
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/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/."
|
||||
@@ -0,0 +1,11 @@
|
||||
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)
|
||||
@@ -5,12 +5,10 @@
|
||||
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 QApplication::exec();
|
||||
return app.exec();
|
||||
}
|
||||
|
||||
@@ -1,149 +1,259 @@
|
||||
# chengnan
|
||||
# Qt + OpenCV 图像显示与处理
|
||||
|
||||
项目链接:<https://git.luochen570.cn/luochen570/chengnan>
|
||||
本工程使用 Qt Widgets 设计界面,使用 OpenCV 完成图像处理。程序支持打开图片、保存图片、另存图片,支持缩放、平移、旋转,并提供目标提取和简单图像分类功能。图像显示使用 Qt 的 `QLabel`/`QWidget`,没有使用 `cv::imshow`。
|
||||
|
||||
`chengnan` 是一个轻量级 Windows 图片查看器 / 简单图片处理工具,使用 **Qt Widgets + CMake + C++17** 开发。
|
||||
## 文件说明
|
||||
|
||||
- `CMakeLists.txt`:CMake 工程配置。
|
||||
- `main.cpp`:程序入口。
|
||||
- `MainWindow.h`:主窗口类和处理参数声明。
|
||||
- `MainWindow.cpp`:界面、图像读写、Qt 线程和 OpenCV 处理实现。
|
||||
|
||||
## 功能
|
||||
|
||||
当前实现:
|
||||
- 打开图片:读取 `png/jpg/bmp/tif` 等常见格式。
|
||||
- 保存图片:保存当前处理结果。
|
||||
- 另存图片:将处理结果保存为新文件。
|
||||
- 显示对比:左侧显示处理前图像,右侧显示处理后图像。
|
||||
- 基本处理:缩放、水平平移、垂直平移、旋转。
|
||||
- 目标提取:使用灰度化、Otsu 阈值、形态学处理和轮廓检测提取前景目标,并用绿色矩形框标记目标。
|
||||
- 图像分类:根据平均亮度和主色通道给出简单分类,同时显示目标数量。
|
||||
- 线程处理:图像处理工作对象运行在 `QThread` 中,避免阻塞界面。
|
||||
|
||||
- 打开图片:PNG、JPG、JPEG、BMP、GIF、WebP 等 Qt 支持的格式
|
||||
- 保存当前图片
|
||||
- 另存为 PNG / JPG / BMP 等格式
|
||||
- 图片显示:使用 Qt Widgets,不使用 OpenCV 窗口
|
||||
- 缩放:工具栏滑块、放大、缩小、原始大小
|
||||
- 双击图片适配窗口
|
||||
- 旋转:左旋 90°、右旋 90°
|
||||
- 翻转:水平翻转、垂直翻转
|
||||
- 简单处理:灰度化、反色
|
||||
## Windows 构建说明
|
||||
|
||||
## 文件结构
|
||||
本工程使用 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
|
||||
chengnan/
|
||||
├── CMakeLists.txt
|
||||
├── MainWindow.cpp
|
||||
├── MainWindow.h
|
||||
├── build-windows.ps1
|
||||
├── main.cpp
|
||||
└── readme.md
|
||||
Desktop development with C++
|
||||
MSVC v143 x64/x86 build tools
|
||||
Windows 10 SDK 或 Windows 11 SDK
|
||||
C++ CMake tools for Windows
|
||||
```
|
||||
|
||||
## 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:\Qt\6.7.2\msvc2019_64
|
||||
C:\Program Files\Microsoft Visual Studio\2022\Community
|
||||
C:\Program Files\Microsoft Visual Studio\2022\BuildTools
|
||||
```
|
||||
|
||||
不要写成:
|
||||
2. Qt for Windows
|
||||
|
||||
使用 Qt Online Installer 安装 Qt。推荐安装 Qt 6.x,并勾选 MSVC 64 位组件,例如:
|
||||
|
||||
```text
|
||||
C:\Qt
|
||||
Qt 6.6.x
|
||||
MSVC 2019 64-bit 或 MSVC 2022 64-bit
|
||||
Qt Creator
|
||||
```
|
||||
|
||||
### 找不到 MSVC 编译器
|
||||
安装完成后,Qt 路径通常类似:
|
||||
|
||||
请安装 Visual Studio 2022 的 `使用 C++ 的桌面开发`,然后在 “x64 Native Tools Command Prompt for VS 2022” 或已配置 VS 环境的 PowerShell 里运行构建脚本。
|
||||
```text
|
||||
C:\Qt\6.6.0\msvc2019_64
|
||||
C:\Qt\6.6.0\msvc2022_64
|
||||
```
|
||||
|
||||
### exe 复制到其它电脑无法运行
|
||||
该目录下应存在:
|
||||
|
||||
请运行 `build-windows.ps1`,并整体复制 `dist-windows\chengnan` 文件夹,不要只复制单个 `chengnan.exe`。
|
||||
```text
|
||||
C:\Qt\6.6.0\msvc2019_64\lib\cmake\Qt6\Qt6Config.cmake
|
||||
```
|
||||
|
||||
## 开发说明
|
||||
3. OpenCV for Windows
|
||||
|
||||
- `main.cpp`:应用入口,创建并显示主窗口
|
||||
- `MainWindow.h`:主窗口和图片标签类声明
|
||||
- `MainWindow.cpp`:菜单、工具栏、图片显示和处理逻辑
|
||||
- `CMakeLists.txt`:Qt Widgets CMake 构建配置
|
||||
- `build-windows.ps1`:Windows 一键构建与打包脚本
|
||||
- `readme.md`:项目说明文档
|
||||
可以使用 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 或传统机器学习模型。
|
||||
|
||||
Reference in New Issue
Block a user