Compare commits

..
54 Commits
Author SHA1 Message Date
luochen570 f915ba24bc ci: fix SIGPIPE in verify step (grep -q → grep > /dev/null)
Build Windows Release / Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) (push) Failing after 4m2s
2026-05-31 02:33:01 +08:00
luochen570 7fb902567e ci: fix OpenCV DLL discovery in packaging step
Build Windows Release / Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) (push) Failing after 2m24s
2026-05-31 02:28:58 +08:00
luochen570 353a175306 ci: add OpenCV include path via CMAKE_CXX_FLAGS
Build Windows Release / Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) (push) Failing after 2m12s
2026-05-31 02:25:22 +08:00
luochen570 a77e3c3e7a ci: fix OpenCV include path for MinGW cross-compile
Build Windows Release / Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) (push) Failing after 1m47s
2026-05-31 02:19:45 +08:00
luochen570 f20aa192d8 ci: use cmake toolchain file instead of missing mingw64-cmake
Build Windows Release / Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) (push) Failing after 2m28s
2026-05-31 02:06:37 +08:00
luochen570 1bed97c95e ci: add mingw64-cmake for cross-build cmake wrapper
Build Windows Release / Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) (push) Failing after 1m58s
2026-05-31 01:46:14 +08:00
luochen570 9a250e1e04 ci: add nodejs for actions/checkout JS runner
Build Windows Release / Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) (push) Failing after 3m36s
2026-05-31 01:29:24 +08:00
luochen570 d2ef431f8c ci: switch Fedora mirror to Aliyun (faster from Shanxi)
Build Windows Release / Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) (push) Failing after 2m1s
2026-05-31 01:26:30 +08:00
luochen570 7eaa200d5f ci: remove unavailable Fedora MinGW Qt package
Build Windows Release / Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) (push) Failing after 39m34s
2026-05-31 00:25:49 +08:00
luochen570 99bc287556 ci: use TUNA Fedora mirror
Build Windows Release / Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) (push) Failing after 12s
2026-05-30 23:20:00 +08:00
luochen570 573c9d746c Implement Qt OpenCV image processing app
Build Windows Release / Build Windows x64 Release on Linux (MinGW + Qt + OpenCV) (push) Failing after 2m15s
2026-05-30 23:09:27 +08:00
luochen570 03b873d4dd ci: use uv to run Qt installer on Windows
Build Windows Release / Build Windows x64 Release (MSVC + Qt) (push) Failing after 1m41s
2026-05-30 22:05:22 +08:00
luochen570 1701f36942 ci: wait for Python installer on Windows
Build Windows Release / Build Windows x64 Release (MSVC + Qt) (push) Failing after 49s
2026-05-30 22:03:08 +08:00
luochen570 9bd4433498 ci: install Python for Qt setup on Windows
Build Windows Release / Build Windows x64 Release (MSVC + Qt) (push) Failing after 50s
2026-05-30 22:01:04 +08:00
luochen570 0717efe807 ci: build Windows release with MSVC Qt
Build Windows Release / Build Windows x64 Release (MSVC + Qt) (push) Failing after -2s
2026-05-30 21:59:27 +08:00
luochen570 081a04de90 ci: rerun Windows release with token
Build Windows Release / Build Windows x64 Release (push) Successful in 1m26s
2026-05-30 21:40:03 +08:00
luochen570 e6405ad09d ci: fix PowerShell status interpolation
Build Windows Release / Build Windows x64 Release (push) Failing after 24s
2026-05-30 21:31:06 +08:00
luochen570 2968dd7caa ci: avoid cross-step env in Windows workflow
Build Windows Release / Build Windows x64 Release (push) Failing after 25s
2026-05-30 21:29:49 +08:00
luochen570 aa18669312 ci: package from fixed runner temp path
Build Windows Release / Build Windows x64 Release (push) Failing after 25s
2026-05-30 21:27:23 +08:00
luochen570 cffa806267 ci: use fixed source path across runner steps
Build Windows Release / Build Windows x64 Release (push) Failing after 24s
2026-05-30 21:16:55 +08:00
luochen570 37ee80e3e7 ci: avoid non-ascii PowerShell literals
Build Windows Release / Build Windows x64 Release (push) Failing after 15s
2026-05-30 21:02:23 +08:00
luochen570 ce5918e4c0 ci: make Windows workflow PowerShell 5 compatible
Build Windows Release / Build Windows x64 Release (push) Failing after -3s
2026-05-30 21:01:21 +08:00
luochen570 a2c9097496 ci: build Windows package without JS actions
Build Windows Release / Build Windows x64 Release (push) Failing after -3s
2026-05-30 20:59:11 +08:00
luochen570 1ff605bc91 ci: target registered Windows runner label
Build Windows Release / Build Windows x64 Release (push) Failing after 32s
2026-05-30 20:54:29 +08:00
luochen570 b0f8695a25 ci: build release on Windows runner
Build Windows Release / Build Windows x64 Release (push) Has been cancelled
2026-05-30 20:50:34 +08:00
luochen570 83ac7ada50 ci: use Linux runner for Windows release
Build Windows Release / Cross build Windows x86_64 Release (push) Has been cancelled
2026-05-30 20:44:24 +08:00
luochen570 56964d71fc ci: add Windows release workflow
Build Windows Release / Build Windows x64 Release (push) Has been cancelled
2026-05-30 20:41:46 +08:00
luochen570 fc9f66d56d docs: add Windows build instructions and script 2026-05-30 17:24:05 +08:00
luochen570 4627343e31 feat: add simplified Qt image viewer Dev branch 2026-05-30 17:18:55 +08:00
luochen570 4832838a0d ci: upload build outputs to repository release
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 0s
Build Windows Release with MSYS2 / build-windows-msys2 (push) Has been cancelled
2026-05-30 14:11:23 +08:00
luochen570 8f6152a382 ci: try uploading unsplit release package 2026-05-30 14:07:48 +08:00
luochen570 add0a6758e ci: use GitHub action steps on proxied runner 2026-05-30 14:06:14 +08:00
luochen570 796a2b7712 ci: add MSYS2 Windows release workflow
Cross Build Windows Release on Linux / cross-build-windows (push) Successful in 5m41s
Build Windows Release with MSYS2 / build-windows-msys2 (push) Has been cancelled
2026-05-30 13:36:59 +08:00
luochen570 8f4579f97c ci: split cross build package uploads
Cross Build Windows Release on Linux / cross-build-windows (push) Successful in 5m7s
2026-05-30 01:34:14 +08:00
luochen570 4e8b0d5f06 ci: use package secret for upload
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 5m30s
2026-05-30 01:22:11 +08:00
luochen570 f8449a5480 ci: use package token for Gitea upload
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m43s
2026-05-30 01:11:00 +08:00
luochen570 5c0f1a1409 ci: verify cross package checksum from output directory
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m48s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 01:04:21 +08:00
luochen570 4793f21f2b ci: fix Fedora mingw OpenCV include path
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m47s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 01:01:23 +08:00
luochen570 d1be6d1f24 ci: use available Fedora mingw packages
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m44s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:51:54 +08:00
luochen570 1e34b10542 ci: avoid deleting checkout source during rsync
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 16s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:46:13 +08:00
luochen570 ae12b48973 ci: use latest Fedora image for cross build
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m10s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:42:29 +08:00
luochen570 4e530cb1dc ci: use supported Fedora image for cross build
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 1m34s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:30:23 +08:00
luochen570 9297fde7ea ci: disable Fedora OpenH264 repo in cross build
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 2s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:28:58 +08:00
luochen570 0ab0ea21c3 ci: use TUNA mirror for Fedora packages
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 2s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:27:57 +08:00
luochen570 4da3e64fcf ci: avoid remote actions in cross build
Cross Build Windows Release on Linux / cross-build-windows (push) Has been cancelled
Build Windows Release / build-windows (push) Has been cancelled
2026-05-30 00:12:49 +08:00
luochen570 f3fb7e877c ci: use 9950x runner for Linux cross build
Cross Build Windows Release on Linux / cross-build-windows (push) Failing after 31s
Build Windows Release / build-windows (push) Has been cancelled
2026-05-29 23:46:42 +08:00
luochen570 f63480b5c2 ci: cross build Windows release on Linux
Cross Build Windows Release on Linux / cross-build-windows (push) Has been cancelled
Build Windows Release / build-windows (push) Has been cancelled
2026-05-29 23:41:51 +08:00
luochen570 6ff03ca32e ci: target self-hosted Windows runner
Build Windows Release / build-windows (push) Has been cancelled
2026-05-29 23:34:19 +08:00
luochen570 7df5312e16 chore: keep build tooling in workflow only
Build Windows Release / build-windows (push) Has been cancelled
2026-05-29 23:05:25 +08:00
luochen570 2a70d6245e ci: build Windows release package
Build Windows Release / build-windows (push) Has been cancelled
2026-05-29 22:59:55 +08:00
luochen570 8c9a92f2cb ci: build Linux release package
Build Linux Release / build-linux (push) Has been cancelled
2026-05-29 22:51:24 +08:00
luochen570 be4446c990 chore: use make for Linux binary dependency setup 2026-05-29 22:41:13 +08:00
luochen570 70a3e39397 Document Linux build toolchain versions 2026-05-29 22:31:49 +08:00
luochen570 81d586c032 Initial Linux Qt OpenCV project 2026-05-29 22:29:38 +08:00
11 changed files with 742 additions and 778 deletions
+35 -41
View File
@@ -5,7 +5,7 @@ on:
branches:
- main
tags:
- "v*"
- 'v*'
workflow_dispatch:
permissions:
@@ -13,17 +13,16 @@ permissions:
jobs:
build-windows-release:
name: Windows x64 Release (MinGW + Qt + OpenCV)
name: Build Windows x64 Release on Linux (MinGW + Qt + OpenCV)
runs-on: ubuntu-latest
container: fedora:latest
env:
BUILD_TYPE: Release
APP_NAME: QtOpenCVImageTool
PACKAGE_BASENAME: QtOpenCVImageTool-windows-x64
PACKAGE_BASENAME: chengnan-windows-x64-mingw
steps:
- name: Configure Fedora mirror
- name: Configure Fedora TUNA mirror
run: |
set -euo pipefail
sed -e 's|^metalink=|#metalink=|g' \
@@ -35,7 +34,7 @@ jobs:
dnf clean all
dnf makecache --refresh -y
- name: Install dependencies
- name: Install cross build dependencies
run: |
set -euo pipefail
dnf install -y \
@@ -56,7 +55,7 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- name: Configure
- name: Configure cross build
run: |
cmake -S . -B build-windows -G Ninja \
-DCMAKE_TOOLCHAIN_FILE=/usr/share/mingw/toolchain-mingw64.cmake \
@@ -67,15 +66,15 @@ jobs:
- name: Build
run: cmake --build build-windows --config "$BUILD_TYPE" --parallel
- name: Package
- name: Package Windows app
run: |
set -euo pipefail
root="/usr/x86_64-w64-mingw32/sys-root/mingw"
dist="dist-windows/$APP_NAME"
rm -rf dist-windows artifacts
dist="dist-windows/chengnan"
rm -rf "$dist" artifacts
mkdir -p "$dist/platforms" "$dist/imageformats" artifacts
cp "build-windows/$APP_NAME.exe" "$dist/"
cp build-windows/chengnan.exe "$dist/"
cp "$root/bin/Qt6Core.dll" "$dist/"
cp "$root/bin/Qt6Gui.dll" "$dist/"
cp "$root/bin/Qt6Widgets.dll" "$dist/"
@@ -84,17 +83,19 @@ jobs:
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*.dll" -exec cp -t "$dist/" {} +
find "$root/bin" -maxdepth 1 -name "*opencv*" -exec cp -t "$dist/" {} +
install -m 0644 readme.md "$dist/readme.md"
cat > "$dist/README.txt" <<EOF
$APP_NAME Windows x64 package
cat > "$dist/README.txt" <<'EOF'
chengnan Windows x64 package
Usage:
1. Extract the whole directory.
2. Double-click $APP_NAME.exe to run.
2. Double-click chengnan.exe to run.
Do not copy the exe alone. Keep DLL files and Qt plugin directories together.
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}"
@@ -103,9 +104,8 @@ jobs:
else
version="build-$short_sha"
fi
package="$PACKAGE_BASENAME-$version.zip"
(cd dist-windows && zip -r "../artifacts/$package" "$APP_NAME")
(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"
@@ -115,19 +115,19 @@ jobs:
set -euo pipefail
test -s "artifacts/$PACKAGE"
test -s "artifacts/$PACKAGE.sha256"
unzip -l "artifacts/$PACKAGE" | grep -E "$APP_NAME/$APP_NAME.exe" > /dev/null
unzip -l "artifacts/$PACKAGE" | grep -E "$APP_NAME/platforms/qwindows.dll" > /dev/null
unzip -l "artifacts/$PACKAGE" | grep -E "$APP_NAME/.*opencv.*\.dll" > /dev/null
unzip -l "artifacts/$PACKAGE" | grep -E 'chengnan/chengnan.exe' > /dev/null
unzip -l "artifacts/$PACKAGE" | grep -E 'chengnan/platforms/qwindows.dll' > /dev/null
unzip -l "artifacts/$PACKAGE" | grep -E 'chengnan/.*opencv.*\.dll' > /dev/null
sha256sum -c "artifacts/$PACKAGE.sha256"
- name: Upload package to Gitea release
- name: Upload package to repository release
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
set -euo pipefail
token="${RELEASE_TOKEN:-${GITHUB_TOKEN:-}}"
if [ -z "$token" ]; then
echo "Missing token. Configure RELEASE_TOKEN in repository secrets or enable GITHUB_TOKEN permissions." >&2
echo 'Missing release token. Configure RELEASE_TOKEN in repository secrets or ensure GITHUB_TOKEN is available.' >&2
exit 1
fi
@@ -139,21 +139,21 @@ jobs:
release_name="$GITHUB_REF_NAME"
else
prerelease=true
release_name="$APP_NAME ${GITHUB_SHA::10}"
release_name="chengnan ${GITHUB_SHA::10}"
fi
release_payload=$(jq -n \
--arg tag_name "$tag_name" \
--arg target_commitish "$GITHUB_SHA" \
--arg name "$release_name" \
--arg body "Automated Windows x64 build for $APP_NAME." \
--arg body "Automated Windows x64 MinGW build from Linux Gitea Actions." \
--argjson prerelease "$prerelease" \
'{tag_name:$tag_name,target_commitish:$target_commitish,name:$name,body:$body,draft:false,prerelease:$prerelease}')
status=$(curl --silent --show-error --location \
--header "Authorization: token $token" \
--header "Content-Type: application/json" \
--write-out "%{http_code}" \
--header 'Content-Type: application/json' \
--write-out '%{http_code}' \
--output release.json \
--data "$release_payload" \
"$api_base/releases")
@@ -165,9 +165,9 @@ jobs:
"$api_base/releases/tags/$tag_name"
fi
release_id=$(jq -r ".id" release.json)
release_id=$(jq -r '.id' release.json)
if [ -z "$release_id" ] || [ "$release_id" = "null" ]; then
echo "Failed to resolve release id." >&2
echo 'Failed to resolve release id.' >&2
cat release.json >&2
exit 1
fi
@@ -176,28 +176,22 @@ jobs:
local path="$1"
local name
name=$(basename "$path")
curl --silent --show-error --location \
--header "Authorization: token $token" \
"$api_base/releases/$release_id/assets" > assets.json
jq -r --arg name "$name" '.[] | select(.name == $name) | .id' assets.json | while read -r asset_id; do
if [ -n "$asset_id" ]; then
curl --silent --show-error --location \
--request DELETE \
--header "Authorization: token $token" \
"$api_base/releases/assets/$asset_id" >/dev/null
fi
[ -n "$asset_id" ] && curl --silent --show-error --location \
--request DELETE \
--header "Authorization: token $token" \
"$api_base/releases/assets/$asset_id" >/dev/null
done
encoded_name=$(python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1]))' "$name")
status=$(curl --silent --show-error --location \
--header "Authorization: token $token" \
--form "attachment=@$path;filename=$name" \
--write-out "%{http_code}" \
--write-out '%{http_code}' \
--output upload-response.json \
"$api_base/releases/$release_id/assets?name=$encoded_name")
"$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
-14
View File
@@ -1,14 +0,0 @@
build/
build-windows/
build-wsl-windows/
cmake-build-*/
.qt/
.qtc/
CMakeUserPresets.json
*.user
*.suo
*.vcxproj*
*.sln
*.exe
*.dll
*.pdb
+34 -21
View File
@@ -1,30 +1,43 @@
cmake_minimum_required(VERSION 3.16)
project(QtOpenCVImageTool LANGUAGES CXX)
project(chengnan VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOUIC OFF)
set(CMAKE_AUTORCC OFF)
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)
find_package(OpenCV REQUIRED)
find_package(OpenCV REQUIRED COMPONENTS core imgproc imgcodecs)
add_executable(QtOpenCVImageTool WIN32
main.cpp
MainWindow.h
MainWindow.cpp
)
target_link_libraries(QtOpenCVImageTool PRIVATE
Qt${QT_VERSION_MAJOR}::Widgets
${OpenCV_LIBS}
)
target_include_directories(QtOpenCVImageTool PRIVATE ${OpenCV_INCLUDE_DIRS})
if(QT_VERSION_MAJOR EQUAL 6)
qt_finalize_executable(QtOpenCVImageTool)
find_package(Qt6 QUIET COMPONENTS Widgets)
if (Qt6_FOUND)
qt_add_executable(chengnan
main.cpp
MainWindow.h
MainWindow.cpp
)
target_link_libraries(chengnan PRIVATE Qt6::Widgets ${OpenCV_LIBS})
else()
find_package(Qt5 REQUIRED COMPONENTS Widgets)
add_executable(chengnan
main.cpp
MainWindow.h
MainWindow.cpp
)
target_link_libraries(chengnan PRIVATE Qt5::Widgets ${OpenCV_LIBS})
endif()
target_include_directories(chengnan PRIVATE ${OpenCV_INCLUDE_DIRS})
target_compile_definitions(chengnan PRIVATE
CHENGNAN_APP_VERSION="${PROJECT_VERSION}"
)
if (MSVC)
target_compile_options(chengnan PRIVATE /W4 /permissive-)
else()
target_compile_options(chengnan PRIVATE -Wall -Wextra -Wpedantic)
endif()
install(TARGETS chengnan RUNTIME DESTINATION bin)
+472 -297
View File
@@ -1,433 +1,608 @@
#include "MainWindow.h"
#include <QCheckBox>
#include <QAction>
#include <QApplication>
#include <QFileDialog>
#include <QFileInfo>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QImage>
#include <QLabel>
#include <QImageReader>
#include <QImageWriter>
#include <QKeySequence>
#include <QMenuBar>
#include <QMessageBox>
#include <QPushButton>
#include <QPixmap>
#include <QScrollArea>
#include <QMouseEvent>
#include <QScrollBar>
#include <QSlider>
#include <QSplitter>
#include <QStatusBar>
#include <QThread>
#include <QVBoxLayout>
#include <QToolBar>
#include <QTransform>
#include <opencv2/imgproc.hpp>
#include <algorithm>
#include <cmath>
#include <exception>
#include <memory>
namespace
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 rgb;
cv::Mat rgba;
if (mat.channels() == 1) {
cv::cvtColor(mat, rgb, cv::COLOR_GRAY2RGB);
cv::cvtColor(mat, rgba, cv::COLOR_GRAY2RGBA);
} else if (mat.channels() == 3) {
cv::cvtColor(mat, rgb, cv::COLOR_BGR2RGB);
} else if (mat.channels() == 4) {
cv::cvtColor(mat, rgb, cv::COLOR_BGRA2RGBA);
cv::cvtColor(mat, rgba, cv::COLOR_BGR2RGBA);
} else {
return {};
cv::cvtColor(mat, rgba, cv::COLOR_BGRA2RGBA);
}
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();
return QImage(rgba.data, rgba.cols, rgba.rows, static_cast<int>(rgba.step), QImage::Format_RGBA8888).copy();
}
cv::Mat rotateWithBounds(const cv::Mat &image, double angle)
QImage extractObjectImage(const QImage &image)
{
if (image.empty() || std::abs(angle) < 0.01) {
return image.clone();
}
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 {};
}
const cv::Mat rgba = qImageToMat(image);
cv::Mat gray;
cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
cv::GaussianBlur(gray, gray, cv::Size(5, 5), 0);
cv::cvtColor(rgba, gray, cv::COLOR_RGBA2GRAY);
cv::GaussianBlur(gray, gray, cv::Size(5, 5), 0.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);
cv::Mat edges;
cv::Canny(gray, edges, 60, 160);
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);
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 < 300.0) {
if (area < 120.0) {
continue;
}
++targetCount;
cv::rectangle(extracted, cv::boundingRect(contour), cv::Scalar(0, 255, 0), 2);
const cv::Rect rect = cv::boundingRect(contour);
cv::rectangle(output, rect, cv::Scalar(0, 0, 255, 255), 2);
++count;
}
return extracted;
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);
}
QString classifyImage(const cv::Mat &image, int targetCount)
QImage classifyImageByOpenCv(const QImage &image)
{
if (image.empty()) {
return QStringLiteral("未载入图片");
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::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);
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);
}
class ImageProcessorWorker : public QObject
} // namespace
ImageLabel::ImageLabel(QWidget *parent)
: QLabel(parent)
{
Q_OBJECT
setAlignment(Qt::AlignCenter);
setBackgroundRole(QPalette::Base);
setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
setScaledContents(false);
setMinimumSize(320, 240);
setText(tr("打开一张图片开始查看"));
}
public slots:
void process(const cv::Mat &source, const ProcessParams &params)
{
if (source.empty()) {
emit processed(cv::Mat(), QStringLiteral("未载入图片"));
return;
}
cv::Mat output = source.clone();
if (std::abs(params.scale - 1.0) > 0.001) {
cv::resize(output, output, cv::Size(), params.scale, params.scale, cv::INTER_LINEAR);
}
output = translateImage(output, params.translateX, params.translateY);
output = rotateWithBounds(output, params.angle);
int targetCount = 0;
if (params.extractTarget) {
output = extractTargets(output, targetCount);
} else {
cv::Mat gray;
cv::cvtColor(output, gray, cv::COLOR_BGR2GRAY);
cv::Mat binary;
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
std::vector<std::vector<cv::Point>> contours;
cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
targetCount = static_cast<int>(std::count_if(contours.begin(), contours.end(), [](const auto &contour) {
return cv::contourArea(contour) >= 300.0;
}));
}
const QString classText = params.classifyImage ? classifyImage(output, targetCount) : QStringLiteral("处理完成");
emit processed(output, classText);
void ImageLabel::mouseDoubleClickEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
Q_EMIT doubleClicked();
}
signals:
void processed(const cv::Mat &image, const QString &classText);
};
QLabel::mouseDoubleClickEvent(event);
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
qRegisterMetaType<cv::Mat>("cv::Mat");
qRegisterMetaType<ProcessParams>("ProcessParams");
createActions();
createMenus();
createToolbar();
createCentralWidget();
updateActions();
buildUi();
auto *worker = new ImageProcessorWorker;
workerThread = new QThread(this);
worker->moveToThread(workerThread);
connect(this, &MainWindow::processRequested, worker, &ImageProcessorWorker::process);
connect(worker, &ImageProcessorWorker::processed, this, &MainWindow::onProcessed);
connect(workerThread, &QThread::finished, worker, &QObject::deleteLater);
workerThread->start();
setWindowTitle(tr("chengnan 图片处理工具"));
resize(1200, 720);
statusBar()->showMessage(tr("就绪"));
}
MainWindow::~MainWindow()
void MainWindow::createActions()
{
if (workerThread) {
workerThread->quit();
workerThread->wait();
}
openAction_ = new QAction(tr("打开(&O)"), this);
openAction_->setShortcut(QKeySequence::Open);
connect(openAction_, &QAction::triggered, this, &MainWindow::openImage);
saveAction_ = new QAction(tr("保存(&S)"), this);
saveAction_->setShortcut(QKeySequence::Save);
connect(saveAction_, &QAction::triggered, this, &MainWindow::saveImage);
saveAsAction_ = new QAction(tr("另存为(&A)"), this);
saveAsAction_->setShortcut(QKeySequence::SaveAs);
connect(saveAsAction_, &QAction::triggered, this, &MainWindow::saveImageAs);
exitAction_ = new QAction(tr("退出(&X)"), this);
exitAction_->setShortcut(QKeySequence::Quit);
connect(exitAction_, &QAction::triggered, this, &QWidget::close);
zoomInAction_ = new QAction(tr("放大"), this);
zoomInAction_->setShortcut(QKeySequence::ZoomIn);
connect(zoomInAction_, &QAction::triggered, this, &MainWindow::zoomIn);
zoomOutAction_ = new QAction(tr("缩小"), this);
zoomOutAction_->setShortcut(QKeySequence::ZoomOut);
connect(zoomOutAction_, &QAction::triggered, this, &MainWindow::zoomOut);
fitAction_ = new QAction(tr("适配窗口"), this);
fitAction_->setShortcut(Qt::CTRL | Qt::Key_F);
connect(fitAction_, &QAction::triggered, this, &MainWindow::fitToWindow);
resetAction_ = new QAction(tr("原始大小"), this);
resetAction_->setShortcut(Qt::CTRL | Qt::Key_0);
connect(resetAction_, &QAction::triggered, this, &MainWindow::resetView);
rotateLeftAction_ = new QAction(tr("左旋 90°"), this);
connect(rotateLeftAction_, &QAction::triggered, this, &MainWindow::rotateLeft);
rotateRightAction_ = new QAction(tr("右旋 90°"), this);
connect(rotateRightAction_, &QAction::triggered, this, &MainWindow::rotateRight);
flipHorizontalAction_ = new QAction(tr("水平翻转"), this);
connect(flipHorizontalAction_, &QAction::triggered, this, &MainWindow::flipHorizontal);
flipVerticalAction_ = new QAction(tr("垂直翻转"), this);
connect(flipVerticalAction_, &QAction::triggered, this, &MainWindow::flipVertical);
grayscaleAction_ = new QAction(tr("灰度化"), this);
connect(grayscaleAction_, &QAction::triggered, this, &MainWindow::grayscale);
invertAction_ = new QAction(tr("反色"), this);
connect(invertAction_, &QAction::triggered, this, &MainWindow::invertColors);
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::buildUi()
void MainWindow::createMenus()
{
setWindowTitle(QStringLiteral("Qt + OpenCV 图像显示与处理"));
QMenu *fileMenu = menuBar()->addMenu(tr("文件(&F)"));
fileMenu->addAction(openAction_);
fileMenu->addAction(saveAction_);
fileMenu->addAction(saveAsAction_);
fileMenu->addSeparator();
fileMenu->addAction(exitAction_);
auto *central = new QWidget(this);
auto *rootLayout = new QVBoxLayout(central);
QMenu *viewMenu = menuBar()->addMenu(tr("查看(&V)"));
viewMenu->addAction(zoomInAction_);
viewMenu->addAction(zoomOutAction_);
viewMenu->addAction(fitAction_);
viewMenu->addAction(resetAction_);
auto *buttonLayout = new QHBoxLayout;
openButton = new QPushButton(QStringLiteral("打开图片"));
saveButton = new QPushButton(QStringLiteral("保存图片"));
saveAsButton = new QPushButton(QStringLiteral("另存图片"));
resetButton = new QPushButton(QStringLiteral("重置处理"));
buttonLayout->addWidget(openButton);
buttonLayout->addWidget(saveButton);
buttonLayout->addWidget(saveAsButton);
buttonLayout->addStretch();
buttonLayout->addWidget(resetButton);
QMenu *processMenu = menuBar()->addMenu(tr("处理(&P)"));
processMenu->addAction(rotateLeftAction_);
processMenu->addAction(rotateRightAction_);
processMenu->addAction(flipHorizontalAction_);
processMenu->addAction(flipVerticalAction_);
processMenu->addSeparator();
processMenu->addAction(grayscaleAction_);
processMenu->addAction(invertAction_);
processMenu->addSeparator();
processMenu->addAction(extractAction_);
processMenu->addAction(classifyAction_);
}
auto *controlBox = new QGroupBox(QStringLiteral("图像处理"));
auto *controlLayout = new QHBoxLayout(controlBox);
void MainWindow::createToolbar()
{
QToolBar *toolbar = addToolBar(tr("主工具栏"));
toolbar->setMovable(false);
toolbar->addAction(openAction_);
toolbar->addAction(saveAction_);
toolbar->addSeparator();
toolbar->addAction(zoomOutAction_);
scaleSlider = new QSlider(Qt::Horizontal);
scaleSlider->setRange(25, 200);
scaleSlider->setValue(100);
rotateSlider = new QSlider(Qt::Horizontal);
rotateSlider->setRange(-180, 180);
translateXSlider = new QSlider(Qt::Horizontal);
translateXSlider->setRange(-200, 200);
translateYSlider = new QSlider(Qt::Horizontal);
translateYSlider->setRange(-200, 200);
extractCheckBox = new QCheckBox(QStringLiteral("目标提取"));
classifyCheckBox = new QCheckBox(QStringLiteral("图像分类"));
zoomSlider_ = new QSlider(Qt::Horizontal, this);
zoomSlider_->setRange(10, 400);
zoomSlider_->setValue(100);
zoomSlider_->setFixedWidth(180);
zoomSlider_->setToolTip(tr("缩放比例"));
connect(zoomSlider_, &QSlider::valueChanged, this, &MainWindow::updateZoomFromSlider);
toolbar->addWidget(zoomSlider_);
auto addSlider = [controlLayout](const QString &name, QSlider *slider) {
auto *box = new QWidget;
auto *layout = new QVBoxLayout(box);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(new QLabel(name));
layout->addWidget(slider);
controlLayout->addWidget(box, 1);
};
toolbar->addAction(zoomInAction_);
toolbar->addAction(fitAction_);
toolbar->addSeparator();
toolbar->addAction(rotateLeftAction_);
toolbar->addAction(rotateRightAction_);
toolbar->addAction(grayscaleAction_);
toolbar->addAction(invertAction_);
toolbar->addAction(extractAction_);
toolbar->addAction(classifyAction_);
}
addSlider(QStringLiteral("缩放"), scaleSlider);
addSlider(QStringLiteral("旋转"), rotateSlider);
addSlider(QStringLiteral("水平平移"), translateXSlider);
addSlider(QStringLiteral("垂直平移"), translateYSlider);
controlLayout->addWidget(extractCheckBox);
controlLayout->addWidget(classifyCheckBox);
void MainWindow::createCentralWidget()
{
originalLabel_ = new ImageLabel(this);
processedLabel_ = new ImageLabel(this);
originalLabel_->setText(tr("处理前图像"));
processedLabel_->setText(tr("处理后图像"));
connect(originalLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow);
connect(processedLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow);
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; }");
originalScrollArea_ = new QScrollArea(this);
originalScrollArea_->setBackgroundRole(QPalette::Dark);
originalScrollArea_->setWidget(originalLabel_);
originalScrollArea_->setWidgetResizable(true);
auto *originalScroll = new QScrollArea;
auto *resultScroll = new QScrollArea;
originalScroll->setWidget(originalLabel);
resultScroll->setWidget(resultLabel);
originalScroll->setWidgetResizable(true);
resultScroll->setWidgetResizable(true);
processedScrollArea_ = new QScrollArea(this);
processedScrollArea_->setBackgroundRole(QPalette::Dark);
processedScrollArea_->setWidget(processedLabel_);
processedScrollArea_->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);
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()
{
const QString fileName = QFileDialog::getOpenFileName(
this,
QStringLiteral("打开图片"),
tr("打开图片"),
QString(),
QStringLiteral("Images (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)"));
tr("图片文件 (*.png *.jpg *.jpeg *.bmp *.gif *.webp);;所有文件 (*.*)"));
if (fileName.isEmpty()) {
return;
}
originalImage = cv::imread(fileName.toLocal8Bit().constData(), cv::IMREAD_COLOR);
if (originalImage.empty()) {
QMessageBox::warning(this, QStringLiteral("打开失败"), QStringLiteral("无法读取该图片文件。"));
QImageReader reader(fileName);
reader.setAutoTransform(true);
const QImage image = reader.read();
if (image.isNull()) {
QMessageBox::warning(this, tr("打开失败"), tr("无法读取图片:%1").arg(reader.errorString()));
return;
}
savePath.clear();
updateOriginalView();
scheduleProcessing();
statusLabel->setText(QStringLiteral("已打开:%1").arg(QFileInfo(fileName).fileName()));
setImage(image, fileName);
}
void MainWindow::saveImage()
{
if (savePath.isEmpty()) {
if (!ensureImageLoaded(tr("保存"))) {
return;
}
if (currentPath_.isEmpty()) {
saveImageAs();
return;
}
if (writeResultToFile(savePath)) {
statusLabel->setText(QStringLiteral("已保存:%1").arg(QFileInfo(savePath).fileName()));
}
writeImageToPath(currentPath_);
}
void MainWindow::saveImageAs()
{
if (resultImage.empty()) {
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("请先打开并处理图片。"));
if (!ensureImageLoaded(tr("另存为"))) {
return;
}
const QString fileName = QFileDialog::getSaveFileName(
this,
QStringLiteral("另存图片"),
QStringLiteral("processed.png"),
QStringLiteral("PNG (*.png);;JPEG (*.jpg *.jpeg);;BMP (*.bmp);;TIFF (*.tif *.tiff)"));
tr("另存为"),
currentPath_.isEmpty() ? QStringLiteral("chengnan.png") : currentPath_,
tr("PNG 图片 (*.png);;JPEG 图片 (*.jpg *.jpeg);;BMP 图片 (*.bmp);;所有文件 (*.*)"));
if (fileName.isEmpty()) {
if (!fileName.isEmpty()) {
writeImageToPath(fileName);
}
}
void MainWindow::zoomIn()
{
setZoomFactor(zoomFactor_ * 1.25);
}
void MainWindow::zoomOut()
{
setZoomFactor(zoomFactor_ / 1.25);
}
void MainWindow::fitToWindow()
{
if (!ensureImageLoaded(tr("适配窗口"))) {
return;
}
if (writeResultToFile(fileName)) {
savePath = fileName;
statusLabel->setText(QStringLiteral("已另存为:%1").arg(QFileInfo(fileName).fileName()));
}
}
void MainWindow::resetParams()
{
scaleSlider->setValue(100);
rotateSlider->setValue(0);
translateXSlider->setValue(0);
translateYSlider->setValue(0);
extractCheckBox->setChecked(false);
classifyCheckBox->setChecked(false);
scheduleProcessing();
}
void MainWindow::scheduleProcessing()
{
if (originalImage.empty()) {
const QSize viewportSize = processedScrollArea_->viewport()->size();
const QSize imageSize = currentImage_.size();
if (imageSize.isEmpty()) {
return;
}
emit processRequested(originalImage.clone(), currentParams());
const double xRatio = static_cast<double>(viewportSize.width()) / imageSize.width();
const double yRatio = static_cast<double>(viewportSize.height()) / imageSize.height();
setZoomFactor(std::min(xRatio, yRatio));
}
void MainWindow::onProcessed(const cv::Mat &image, const QString &classText)
void MainWindow::resetView()
{
resultImage = image.clone();
updateResultView();
statusLabel->setText(classText);
setZoomFactor(1.0);
}
void MainWindow::updateOriginalView()
void MainWindow::rotateLeft()
{
setImageOnLabel(originalLabel, originalImage);
if (!ensureImageLoaded(tr("旋转"))) {
return;
}
QTransform transform;
transform.rotate(-90);
applyTransformedImage(currentImage_.transformed(transform, Qt::SmoothTransformation));
}
void MainWindow::updateResultView()
void MainWindow::rotateRight()
{
setImageOnLabel(resultLabel, resultImage);
if (!ensureImageLoaded(tr("旋转"))) {
return;
}
QTransform transform;
transform.rotate(90);
applyTransformedImage(currentImage_.transformed(transform, Qt::SmoothTransformation));
}
void MainWindow::setImageOnLabel(QLabel *label, const cv::Mat &mat)
void MainWindow::flipHorizontal()
{
const QImage image = matToQImage(mat);
if (image.isNull()) {
label->setText(QStringLiteral("无图像"));
if (!ensureImageLoaded(tr("翻转"))) {
return;
}
applyTransformedImage(currentImage_.mirrored(true, false));
}
void MainWindow::flipVertical()
{
if (!ensureImageLoaded(tr("翻转"))) {
return;
}
applyTransformedImage(currentImage_.mirrored(false, true));
}
void MainWindow::grayscale()
{
processImageInThread(tr("灰度化"), tr("灰度化完成,可保存结果"), [](QImage image) {
cv::Mat rgba = qImageToMat(image);
cv::Mat gray;
cv::cvtColor(rgba, gray, cv::COLOR_RGBA2GRAY);
return matToQImage(gray);
});
}
void MainWindow::invertColors()
{
processImageInThread(tr("反色"), tr("反色完成,可保存结果"), [](QImage image) {
QImage result = image.convertToFormat(QImage::Format_ARGB32);
result.invertPixels(QImage::InvertRgb);
return result;
});
}
void MainWindow::extractObjects()
{
processImageInThread(tr("目标提取"), tr("目标提取完成,红框为提取到的目标"), [](QImage image) {
return extractObjectImage(image);
});
}
void MainWindow::classifyImage()
{
processImageInThread(tr("简单分类"), tr("简单分类完成,结果已标注在图像上"), [](QImage image) {
return classifyImageByOpenCv(image);
});
}
void MainWindow::updateZoomFromSlider(int value)
{
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)
{
originalImage_ = image.convertToFormat(QImage::Format_ARGB32);
currentImage_ = originalImage_;
currentPath_ = path;
setZoomFactor(1.0);
updateActions();
const QFileInfo info(path);
setWindowTitle(path.isEmpty()
? tr("chengnan 图片处理工具")
: tr("%1 - chengnan 图片处理工具").arg(info.fileName()));
statusBar()->showMessage(tr("已加载:%1 × %2").arg(currentImage_.width()).arg(currentImage_.height()), 5000);
}
void MainWindow::updateImageView()
{
if (currentImage_.isNull()) {
originalLabel_->setPixmap(QPixmap());
processedLabel_->setPixmap(QPixmap());
originalLabel_->setText(tr("处理前图像"));
processedLabel_->setText(tr("处理后图像"));
return;
}
label->setPixmap(QPixmap::fromImage(image).scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
updateSingleView(originalLabel_, originalImage_);
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));
}
ProcessParams MainWindow::currentParams() const
void MainWindow::updateSingleView(ImageLabel *label, const QImage &image)
{
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;
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,
Qt::KeepAspectRatio,
Qt::SmoothTransformation);
label->setText(QString());
label->setPixmap(pixmap);
label->resize(pixmap.size());
}
bool MainWindow::writeResultToFile(const QString &fileName)
void MainWindow::setZoomFactor(double factor)
{
if (resultImage.empty()) {
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("没有可保存的处理结果。"));
return false;
zoomFactor_ = std::clamp(factor, 0.10, 4.00);
updateImageView();
}
void MainWindow::applyTransformedImage(const QImage &image, const QString &message)
{
currentImage_ = image.convertToFormat(QImage::Format_ARGB32);
updateImageView();
updateActions();
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()
{
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);
extractAction_->setEnabled(hasImage);
classifyAction_->setEnabled(hasImage);
zoomSlider_->setEnabled(hasImage);
}
bool MainWindow::ensureImageLoaded(const QString &actionName) const
{
if (!currentImage_.isNull()) {
return true;
}
if (!cv::imwrite(fileName.toLocal8Bit().constData(), resultImage)) {
QMessageBox::warning(this, QStringLiteral("保存失败"), QStringLiteral("无法写入该图片文件。"));
QMessageBox::information(nullptr, actionName, tr("请先打开一张图片。"));
return false;
}
bool MainWindow::writeImageToPath(const QString &path)
{
QImageWriter writer(path);
if (!writer.write(currentImage_)) {
QMessageBox::warning(this, tr("保存失败"), tr("无法保存图片:%1").arg(writer.errorString()));
return false;
}
currentPath_ = path;
setWindowTitle(tr("%1 - chengnan 图片处理工具").arg(QFileInfo(path).fileName()));
statusBar()->showMessage(tr("已保存:%1").arg(path), 5000);
return true;
}
#include "MainWindow.moc"
+73 -49
View File
@@ -1,76 +1,100 @@
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QImage>
#include <QLabel>
#include <QMainWindow>
#include <QMetaType>
#include <QPixmap>
#include <QScrollArea>
#include <QString>
#include <functional>
#include <opencv2/opencv.hpp>
class QLabel;
class QAction;
class QMenu;
class QPushButton;
class QSlider;
class QCheckBox;
class QThread;
struct ProcessParams
class ImageLabel final : public QLabel
{
double scale = 1.0;
int translateX = 0;
int translateY = 0;
double angle = 0.0;
bool extractTarget = false;
bool classifyImage = false;
Q_OBJECT
public:
explicit ImageLabel(QWidget *parent = nullptr);
Q_SIGNALS:
void doubleClicked();
protected:
void mouseDoubleClickEvent(QMouseEvent *event) override;
};
Q_DECLARE_METATYPE(cv::Mat)
Q_DECLARE_METATYPE(ProcessParams)
class MainWindow : public QMainWindow
class MainWindow final : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow() override;
signals:
void processRequested(const cv::Mat &image, const ProcessParams &params);
private slots:
private Q_SLOTS:
void openImage();
void saveImage();
void saveImageAs();
void resetParams();
void scheduleProcessing();
void onProcessed(const cv::Mat &image, const QString &classText);
void zoomIn();
void zoomOut();
void fitToWindow();
void resetView();
void rotateLeft();
void rotateRight();
void flipHorizontal();
void flipVertical();
void grayscale();
void invertColors();
void extractObjects();
void classifyImage();
void updateZoomFromSlider(int value);
private:
void buildUi();
void updateOriginalView();
void updateResultView();
void setImageOnLabel(QLabel *label, const cv::Mat &mat);
ProcessParams currentParams() const;
bool writeResultToFile(const QString &fileName);
void createActions();
void createMenus();
void createToolbar();
void createCentralWidget();
void setImage(const QImage &image, const QString &path = QString());
void updateImageView();
void updateSingleView(ImageLabel *label, const QImage &image);
void setZoomFactor(double factor);
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();
bool ensureImageLoaded(const QString &actionName) const;
bool writeImageToPath(const QString &path);
QLabel *originalLabel = nullptr;
QLabel *resultLabel = nullptr;
QLabel *statusLabel = nullptr;
QPushButton *openButton = nullptr;
QPushButton *saveButton = nullptr;
QPushButton *saveAsButton = nullptr;
QPushButton *resetButton = nullptr;
QSlider *scaleSlider = nullptr;
QSlider *rotateSlider = nullptr;
QSlider *translateXSlider = nullptr;
QSlider *translateYSlider = nullptr;
QCheckBox *extractCheckBox = nullptr;
QCheckBox *classifyCheckBox = nullptr;
ImageLabel *originalLabel_ = nullptr;
ImageLabel *processedLabel_ = nullptr;
QScrollArea *originalScrollArea_ = nullptr;
QScrollArea *processedScrollArea_ = nullptr;
QSlider *zoomSlider_ = nullptr;
cv::Mat originalImage;
cv::Mat resultImage;
QString savePath;
QImage originalImage_;
QImage currentImage_;
QString currentPath_;
double zoomFactor_ = 1.0;
QThread *workerThread = nullptr;
QAction *openAction_ = nullptr;
QAction *saveAction_ = nullptr;
QAction *saveAsAction_ = nullptr;
QAction *exitAction_ = nullptr;
QAction *zoomInAction_ = nullptr;
QAction *zoomOutAction_ = nullptr;
QAction *fitAction_ = nullptr;
QAction *resetAction_ = nullptr;
QAction *rotateLeftAction_ = nullptr;
QAction *rotateRightAction_ = nullptr;
QAction *flipHorizontalAction_ = nullptr;
QAction *flipVerticalAction_ = nullptr;
QAction *grayscaleAction_ = nullptr;
QAction *invertAction_ = nullptr;
QAction *extractAction_ = nullptr;
QAction *classifyAction_ = nullptr;
};
#endif
#endif // MAINWINDOW_H
Binary file not shown.
-46
View File
@@ -1,46 +0,0 @@
@echo off
setlocal
rem Usage:
rem build_windows.bat C:\Qt\6.6.0\msvc2019_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
rem build_windows.bat C:\Qt\6.6.0\mingw_64 C:\opencv-mingw\install "MinGW Makefiles"
if "%~1"=="" (
echo Usage: %~nx0 ^<QtDir^> ^<OpenCV_DIR^> [CMakeGenerator]
echo Example MSVC : %~nx0 C:\Qt\6.6.0\msvc2019_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
echo Example MinGW: %~nx0 C:\Qt\6.6.0\mingw_64 C:\opencv-mingw\install "MinGW Makefiles"
exit /b 1
)
if "%~2"=="" (
echo Missing OpenCV_DIR.
exit /b 1
)
set QT_DIR=%~1
set OPENCV_DIR=%~2
set GENERATOR=%~3
if "%GENERATOR%"=="" (
set GENERATOR=Visual Studio 17 2022
)
if not exist build-windows (
mkdir build-windows
)
if /I "%GENERATOR%"=="MinGW Makefiles" (
cmake -S . -B build-windows -G "%GENERATOR%" -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="%QT_DIR%" -DOpenCV_DIR="%OPENCV_DIR%"
) else (
cmake -S . -B build-windows -G "%GENERATOR%" -A x64 -DCMAKE_PREFIX_PATH="%QT_DIR%" -DOpenCV_DIR="%OPENCV_DIR%"
)
if errorlevel 1 exit /b %errorlevel%
cmake --build build-windows --config Release
if errorlevel 1 exit /b %errorlevel%
echo.
echo Build finished.
echo For MSVC, check: build-windows\Release\QtOpenCVImageTool.exe
echo For MinGW, check: build-windows\QtOpenCVImageTool.exe
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
if ! command -v x86_64-w64-mingw32-g++ >/dev/null 2>&1; then
echo "Missing x86_64-w64-mingw32-g++."
echo "Install it in WSL with: sudo apt install mingw-w64"
exit 1
fi
if [[ "${QT_MINGW_PREFIX:-}" == "" ]]; then
echo "Missing QT_MINGW_PREFIX."
echo "Example: export QT_MINGW_PREFIX=/opt/mxe/usr/x86_64-w64-mingw32.shared/qt6"
exit 1
fi
if [[ "${OpenCV_DIR:-}" == "" ]]; then
echo "Missing OpenCV_DIR."
echo "Example: export OpenCV_DIR=/opt/mxe/usr/x86_64-w64-mingw32.shared/lib/cmake/opencv4"
exit 1
fi
cmake -S . -B build-wsl-windows \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw64.cmake \
-DCMAKE_PREFIX_PATH="${QT_MINGW_PREFIX}" \
-DOpenCV_DIR="${OpenCV_DIR}"
cmake --build build-wsl-windows --config Release
echo "Windows executable should be under build-wsl-windows/."
-11
View File
@@ -1,11 +0,0 @@
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_PROCESSOR x86_64)
set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++)
set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
+4 -2
View File
@@ -5,10 +5,12 @@
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QApplication::setApplicationName(QStringLiteral("chengnan"));
QApplication::setApplicationVersion(QStringLiteral(CHENGNAN_APP_VERSION));
QApplication::setOrganizationName(QStringLiteral("luochen570"));
MainWindow window;
window.resize(1180, 760);
window.show();
return app.exec();
return QApplication::exec();
}
+124 -267
View File
@@ -1,297 +1,154 @@
# Qt + OpenCV 图像显示与处理
# chengnan
本工程使用 Qt Widgets 设计界面,使用 OpenCV 完成图像处理。程序支持打开图片、保存图片、另存图片,支持缩放、平移、旋转,并提供目标提取和简单图像分类功能。图像显示使用 Qt 的 `QLabel`/`QWidget`,没有使用 `cv::imshow`。
项目链接:<https://git.luochen570.cn/luochen570/chengnan>
## 文件说明
`chengnan` 是一个 Windows 图像显示与处理课程项目,使用 **Qt Widgets + OpenCV + CMake + C++17** 开发。
- `CMakeLists.txt`:CMake 工程配置。
- `main.cpp`:程序入口。
- `MainWindow.h`:主窗口类和处理参数声明。
- `MainWindow.cpp`:界面、图像读写、Qt 线程和 OpenCV 处理实现。
## 作业要求对应情况
- 使用 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/bmp/tif` 等常见格式。
- 保存图片:保存当前处理结果。
- 另存图片:将处理结果保存为新文件。
- 显示对比:左侧显示处理前图像,右侧显示处理后图像。
- 基本处理:缩放、水平平移、垂直平移、旋转。
- 目标提取:使用灰度化、Otsu 阈值、形态学处理和轮廓检测提取前景目标,并用绿色矩形框标记目标。
- 图像分类:根据平均亮度和主色通道给出简单分类,同时显示目标数量。
- 线程处理:图像处理工作对象运行在 `QThread` 中,避免阻塞界面。
当前实现:
## Windows 构建说明
- 打开图片:PNG、JPG、JPEG、BMP、GIF、WebP 等 Qt 支持的格式
- 保存当前处理后图片
- 另存为 PNG / JPG / BMP 等格式
- 处理前 / 处理后双栏对比显示
- 缩放:工具栏滑块、放大、缩小、原始大小
- 平移:放大后使用滚动条移动查看区域
- 双击图片适配窗口
- 旋转:左旋 90°、右旋 90°
- 翻转:水平翻转、垂直翻转
- OpenCV 图片处理:灰度化、目标提取、简单分类
- 其它处理:反色
本工程使用 CMake 管理,目标是构建 Windows 桌面应用程序 `QtOpenCVImageTool.exe`。推荐使用 **MSVC 64 位**,因为 OpenCV 官方 Windows 预编译包通常就是 MSVC 版本,配置最省事。
构建时请保持三者一致:
- 编译器一致:MSVC 对 MSVC,MinGW 对 MinGW。
- 位数一致:建议全部使用 64 位。
- Qt、OpenCV、CMake 使用同一套构建环境。
如果使用 MSVC,则不要混用 MinGW 版 Qt;如果使用 MinGW,则不要直接使用 OpenCV 官方 MSVC 预编译包。
### 需要安装的软件
1. Visual Studio 2022 或 Visual Studio 2022 Build Tools
安装时勾选:
## 文件结构
```text
Desktop development with C++
MSVC v143 x64/x86 build tools
Windows 10 SDK 或 Windows 11 SDK
C++ CMake tools for Windows
chengnan/
├── .gitea/workflows/build-windows-release.yml
├── CMakeLists.txt
├── MainWindow.cpp
├── MainWindow.h
├── main.cpp
└── readme.md
```
安装完成后,系统中应能找到类似路径:
除工作流和 `readme.md` 外,工程根目录只保留 `CMakeLists.txt`、`main.cpp`、`MainWindow.h`、`MainWindow.cpp` 四个文件。
## 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`。
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/>
- 需要安装组件:`使用 C++ 的桌面开发`。
- 提供 MSVC 编译器和 Windows SDK。
## 获取源码
```powershell
git clone https://git.luochen570.cn/luochen570/chengnan.git
cd chengnan
```
## 手动构建
在已配置 Visual Studio C++ 编译环境的 PowerShell 或 “x64 Native Tools Command Prompt for VS 2022” 中执行:
```powershell
cmake -S . -B build-windows -G "Visual Studio 17 2022" -A x64 -DCMAKE_PREFIX_PATH="C:\Qt\6.7.3\msvc2022_64;C:\opencv\build"
cmake --build build-windows --config Release
```
打包 Qt 运行库:
```powershell
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
确认 CMake 的 `CMAKE_PREFIX_PATH` 包含 Qt 套件目录,而不是 Qt 根目录。例如应使用:
```text
C:\Program Files\Microsoft Visual Studio\2022\Community
C:\Program Files\Microsoft Visual Studio\2022\BuildTools
C:\Qt\6.7.3\msvc2022_64
```
2. Qt for Windows
使用 Qt Online Installer 安装 Qt。推荐安装 Qt 6.x,并勾选 MSVC 64 位组件,例如:
不要写成:
```text
Qt 6.6.x
MSVC 2019 64-bit 或 MSVC 2022 64-bit
Qt Creator
C:\Qt
```
安装完成后,Qt 路径通常类似:
### 找不到 OpenCV
确认 CMake 的 `CMAKE_PREFIX_PATH` 包含 OpenCV 的 `build` 目录。例如:
```text
C:\Qt\6.6.0\msvc2019_64
C:\Qt\6.6.0\msvc2022_64
C:\opencv\build
```
该目录下应存在:
该目录下通常能找到 `OpenCVConfig.cmake`。
```text
C:\Qt\6.6.0\msvc2019_64\lib\cmake\Qt6\Qt6Config.cmake
```
### 找不到 MSVC 编译器
3. OpenCV for Windows
请安装 Visual Studio 2022 的 `使用 C++ 的桌面开发`,然后在 “x64 Native Tools Command Prompt for VS 2022” 或已配置 VS 环境的 PowerShell 里运行构建命令。
可以使用 OpenCV 官方 Windows 包。解压或安装到例如:
### exe 复制到其它电脑无法运行
```text
C:\opencv
```
不要只复制单个 `chengnan.exe`。需要同时复制 Qt / OpenCV DLL 和 Qt 插件目录,或直接使用 Gitea Actions 发布的 zip 附件。
常见的 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。
## CI 自动构建和发布
仓库提供了 Gitea Actions 工作流:
```text
.gitea/workflows/build-windows-release.yml
```
触发方式:
- 推送到 `main` 分支。
- 推送 `v*` 标签,例如 `v1.0.0`。
- 在 Gitea 页面手动运行 `workflow_dispatch`。
CI 会在 Fedora 容器中安装 MinGW-w64、Qt6、OpenCV,交叉编译 Windows x64 程序,然后打包:
```text
QtOpenCVImageTool-windows-x64-<version>.zip
QtOpenCVImageTool-windows-x64-<version>.zip.sha256
```
最后通过 Gitea API 上传到仓库 Release。为了允许上传 Release,请在仓库的 Actions Secrets 中配置:
```text
RELEASE_TOKEN=<具有仓库 release 写权限的 token>
```
如果 Gitea 已经给 Actions 提供可写的 `GITHUB_TOKEN`,也可以不配置 `RELEASE_TOKEN`。
发布版本建议使用 tag:
```bash
git tag v1.0.0
git push origin v1.0.0
```
这样 Release 名称和包名会使用 `v1.0.0`。如果只是推送到 `main`,CI 会创建预发布版本,名称类似 `build-提交哈希`。
## WSL 中交叉编译 Windows 程序
WSL 里不能使用 Linux 版 Qt/OpenCV 直接生成 Windows exe,必须准备 Windows 目标库。推荐使用 MinGW-w64 作为交叉编译器,并准备同为 MinGW-w64 目标的 Qt 和 OpenCV。
需要的组件:
- `x86_64-w64-mingw32-g++`
- Windows/MinGW 目标 Qt,目录中应包含 `Qt6Config.cmake` 或 `Qt5Config.cmake`
- Windows/MinGW 目标 OpenCV,目录中应包含 `OpenCVConfig.cmake`
构建脚本:
```bash
export QT_MINGW_PREFIX=/opt/mxe/usr/x86_64-w64-mingw32.shared/qt6
export OpenCV_DIR=/opt/mxe/usr/x86_64-w64-mingw32.shared/lib/cmake/opencv4
./build_wsl_windows.sh
```
如果使用的是自己编译或复制来的 Windows 目标 Qt/OpenCV,把上面两个路径换成实际路径即可。
## 说明
本示例中的分类属于简单规则分类,适合作为课程作业演示:根据图像整体亮度判断“偏亮/偏暗/亮度适中”,根据 BGR 平均值判断主色。若需要更高精度分类,可替换为训练好的 OpenCV DNN 或传统机器学习模型。
- `main.cpp`:应用入口,创建并显示主窗口
- `MainWindow.h`:主窗口和图片标签类声明
- `MainWindow.cpp`:菜单、工具栏、图片显示、OpenCV 图像处理和 Qt 线程逻辑
- `CMakeLists.txt`:Qt Widgets + OpenCV CMake 构建配置
- `readme.md`:项目说明文档