Compare commits
54
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f915ba24bc | ||
|
|
7fb902567e | ||
|
|
353a175306 | ||
|
|
a77e3c3e7a | ||
|
|
f20aa192d8 | ||
|
|
1bed97c95e | ||
|
|
9a250e1e04 | ||
|
|
d2ef431f8c | ||
|
|
7eaa200d5f | ||
|
|
99bc287556 | ||
|
|
573c9d746c | ||
|
|
03b873d4dd | ||
|
|
1701f36942 | ||
|
|
9bd4433498 | ||
|
|
0717efe807 | ||
|
|
081a04de90 | ||
|
|
e6405ad09d | ||
|
|
2968dd7caa | ||
|
|
aa18669312 | ||
|
|
cffa806267 | ||
|
|
37ee80e3e7 | ||
|
|
ce5918e4c0 | ||
|
|
a2c9097496 | ||
|
|
1ff605bc91 | ||
|
|
b0f8695a25 | ||
|
|
83ac7ada50 | ||
|
|
56964d71fc | ||
|
|
fc9f66d56d | ||
|
|
4627343e31 | ||
|
|
4832838a0d | ||
|
|
8f6152a382 | ||
|
|
add0a6758e | ||
|
|
796a2b7712 | ||
|
|
8f4579f97c | ||
|
|
4e8b0d5f06 | ||
|
|
f8449a5480 | ||
|
|
5c0f1a1409 | ||
|
|
4793f21f2b | ||
|
|
d1be6d1f24 | ||
|
|
1e34b10542 | ||
|
|
ae12b48973 | ||
|
|
4e530cb1dc | ||
|
|
9297fde7ea | ||
|
|
0ab0ea21c3 | ||
|
|
4da3e64fcf | ||
|
|
f3fb7e877c | ||
|
|
f63480b5c2 | ||
|
|
6ff03ca32e | ||
|
|
7df5312e16 | ||
|
|
2a70d6245e | ||
|
|
8c9a92f2cb | ||
|
|
be4446c990 | ||
|
|
70a3e39397 | ||
|
|
81d586c032 |
@@ -0,0 +1,205 @@
|
|||||||
|
name: Build Windows Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-windows-release:
|
||||||
|
name: Build Windows x64 Release on Linux (MinGW + Qt + OpenCV)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container: fedora:latest
|
||||||
|
|
||||||
|
env:
|
||||||
|
BUILD_TYPE: Release
|
||||||
|
PACKAGE_BASENAME: chengnan-windows-x64-mingw
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Configure Fedora TUNA mirror
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
sed -e 's|^metalink=|#metalink=|g' \
|
||||||
|
-e 's|^#baseurl=http://download.example/pub/fedora/linux|baseurl=https://mirrors.aliyun.com/fedora|g' \
|
||||||
|
-i /etc/yum.repos.d/fedora*.repo
|
||||||
|
if [ -f /etc/yum.repos.d/fedora-cisco-openh264.repo ]; then
|
||||||
|
sed -i 's|^enabled=1|enabled=0|g' /etc/yum.repos.d/fedora-cisco-openh264.repo
|
||||||
|
fi
|
||||||
|
dnf clean all
|
||||||
|
dnf makecache --refresh -y
|
||||||
|
|
||||||
|
- name: Install cross build dependencies
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
dnf install -y \
|
||||||
|
git \
|
||||||
|
curl \
|
||||||
|
jq \
|
||||||
|
zip \
|
||||||
|
unzip \
|
||||||
|
python3 \
|
||||||
|
nodejs \
|
||||||
|
cmake \
|
||||||
|
ninja-build \
|
||||||
|
mingw64-gcc-c++ \
|
||||||
|
mingw64-qt6-qtbase \
|
||||||
|
mingw64-qt6-qtimageformats \
|
||||||
|
mingw64-opencv
|
||||||
|
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Configure cross build
|
||||||
|
run: |
|
||||||
|
cmake -S . -B build-windows -G Ninja \
|
||||||
|
-DCMAKE_TOOLCHAIN_FILE=/usr/share/mingw/toolchain-mingw64.cmake \
|
||||||
|
-DCMAKE_BUILD_TYPE="$BUILD_TYPE" \
|
||||||
|
-DCMAKE_CXX_FLAGS="-isystem /usr/x86_64-w64-mingw32/sys-root/mingw/include/opencv4" \
|
||||||
|
-DOpenCV_DIR=/usr/x86_64-w64-mingw32/sys-root/mingw/lib/cmake/OpenCV
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: cmake --build build-windows --config "$BUILD_TYPE" --parallel
|
||||||
|
|
||||||
|
- name: Package Windows app
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
root="/usr/x86_64-w64-mingw32/sys-root/mingw"
|
||||||
|
dist="dist-windows/chengnan"
|
||||||
|
rm -rf "$dist" artifacts
|
||||||
|
mkdir -p "$dist/platforms" "$dist/imageformats" artifacts
|
||||||
|
|
||||||
|
cp build-windows/chengnan.exe "$dist/"
|
||||||
|
cp "$root/bin/Qt6Core.dll" "$dist/"
|
||||||
|
cp "$root/bin/Qt6Gui.dll" "$dist/"
|
||||||
|
cp "$root/bin/Qt6Widgets.dll" "$dist/"
|
||||||
|
cp "$root/bin/libgcc_s_seh-1.dll" "$dist/"
|
||||||
|
cp "$root/bin/libstdc++-6.dll" "$dist/"
|
||||||
|
cp "$root/bin/libwinpthread-1.dll" "$dist/"
|
||||||
|
cp "$root/lib/qt6/plugins/platforms/qwindows.dll" "$dist/platforms/"
|
||||||
|
cp "$root/lib/qt6/plugins/imageformats/"*.dll "$dist/imageformats/"
|
||||||
|
find "$root/bin" -maxdepth 1 -name "*opencv*" -exec cp -t "$dist/" {} +
|
||||||
|
install -m 0644 readme.md "$dist/readme.md"
|
||||||
|
|
||||||
|
cat > "$dist/README.txt" <<'EOF'
|
||||||
|
chengnan Windows x64 package
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
1. Extract the whole directory.
|
||||||
|
2. Double-click chengnan.exe to run.
|
||||||
|
|
||||||
|
Note:
|
||||||
|
- This package is cross-built on Linux with MinGW + Qt + OpenCV.
|
||||||
|
- Do not copy chengnan.exe alone; keep DLLs and Qt plugin directories together.
|
||||||
|
EOF
|
||||||
|
|
||||||
|
short_sha="${GITHUB_SHA::10}"
|
||||||
|
if [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then
|
||||||
|
version="$GITHUB_REF_NAME"
|
||||||
|
else
|
||||||
|
version="build-$short_sha"
|
||||||
|
fi
|
||||||
|
package="$PACKAGE_BASENAME-$version.zip"
|
||||||
|
(cd dist-windows && zip -r "../artifacts/$package" chengnan)
|
||||||
|
sha256sum "artifacts/$package" > "artifacts/$package.sha256"
|
||||||
|
printf 'VERSION=%s\n' "$version" >> "$GITHUB_ENV"
|
||||||
|
printf 'PACKAGE=%s\n' "$package" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
|
- name: Verify package
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
test -s "artifacts/$PACKAGE"
|
||||||
|
test -s "artifacts/$PACKAGE.sha256"
|
||||||
|
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 repository release
|
||||||
|
env:
|
||||||
|
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
token="${RELEASE_TOKEN:-${GITHUB_TOKEN:-}}"
|
||||||
|
if [ -z "$token" ]; then
|
||||||
|
echo 'Missing release token. Configure RELEASE_TOKEN in repository secrets or ensure GITHUB_TOKEN is available.' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
server_url="${GITHUB_SERVER_URL%/}"
|
||||||
|
api_base="$server_url/api/v1/repos/$GITHUB_REPOSITORY"
|
||||||
|
tag_name="$VERSION"
|
||||||
|
if [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then
|
||||||
|
prerelease=false
|
||||||
|
release_name="$GITHUB_REF_NAME"
|
||||||
|
else
|
||||||
|
prerelease=true
|
||||||
|
release_name="chengnan ${GITHUB_SHA::10}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
release_payload=$(jq -n \
|
||||||
|
--arg tag_name "$tag_name" \
|
||||||
|
--arg target_commitish "$GITHUB_SHA" \
|
||||||
|
--arg name "$release_name" \
|
||||||
|
--arg body "Automated Windows x64 MinGW build from Linux Gitea Actions." \
|
||||||
|
--argjson prerelease "$prerelease" \
|
||||||
|
'{tag_name:$tag_name,target_commitish:$target_commitish,name:$name,body:$body,draft:false,prerelease:$prerelease}')
|
||||||
|
|
||||||
|
status=$(curl --silent --show-error --location \
|
||||||
|
--header "Authorization: token $token" \
|
||||||
|
--header 'Content-Type: application/json' \
|
||||||
|
--write-out '%{http_code}' \
|
||||||
|
--output release.json \
|
||||||
|
--data "$release_payload" \
|
||||||
|
"$api_base/releases")
|
||||||
|
|
||||||
|
if [ "$status" != "200" ] && [ "$status" != "201" ]; then
|
||||||
|
curl --silent --show-error --location \
|
||||||
|
--header "Authorization: token $token" \
|
||||||
|
--output release.json \
|
||||||
|
"$api_base/releases/tags/$tag_name"
|
||||||
|
fi
|
||||||
|
|
||||||
|
release_id=$(jq -r '.id' release.json)
|
||||||
|
if [ -z "$release_id" ] || [ "$release_id" = "null" ]; then
|
||||||
|
echo 'Failed to resolve release id.' >&2
|
||||||
|
cat release.json >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
upload_asset() {
|
||||||
|
local path="$1"
|
||||||
|
local name
|
||||||
|
name=$(basename "$path")
|
||||||
|
curl --silent --show-error --location \
|
||||||
|
--header "Authorization: token $token" \
|
||||||
|
"$api_base/releases/$release_id/assets" > assets.json
|
||||||
|
jq -r --arg name "$name" '.[] | select(.name == $name) | .id' assets.json | while read -r asset_id; do
|
||||||
|
[ -n "$asset_id" ] && curl --silent --show-error --location \
|
||||||
|
--request DELETE \
|
||||||
|
--header "Authorization: token $token" \
|
||||||
|
"$api_base/releases/assets/$asset_id" >/dev/null
|
||||||
|
done
|
||||||
|
|
||||||
|
status=$(curl --silent --show-error --location \
|
||||||
|
--header "Authorization: token $token" \
|
||||||
|
--form "attachment=@$path;filename=$name" \
|
||||||
|
--write-out '%{http_code}' \
|
||||||
|
--output upload-response.json \
|
||||||
|
"$api_base/releases/$release_id/assets?name=$(python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1]))' "$name")")
|
||||||
|
if [ "$status" != "200" ] && [ "$status" != "201" ]; then
|
||||||
|
echo "Upload release asset failed, HTTP $status: $name" >&2
|
||||||
|
cat upload-response.json >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Uploaded release asset: $name"
|
||||||
|
}
|
||||||
|
|
||||||
|
upload_asset "artifacts/$PACKAGE"
|
||||||
|
upload_asset "artifacts/$PACKAGE.sha256"
|
||||||
|
echo "Release assets uploaded to $server_url/$GITHUB_REPOSITORY/releases/tag/$tag_name"
|
||||||
-14
@@ -1,14 +0,0 @@
|
|||||||
build/
|
|
||||||
build-windows/
|
|
||||||
build-wsl-windows/
|
|
||||||
cmake-build-*/
|
|
||||||
.qt/
|
|
||||||
.qtc/
|
|
||||||
CMakeUserPresets.json
|
|
||||||
*.user
|
|
||||||
*.suo
|
|
||||||
*.vcxproj*
|
|
||||||
*.sln
|
|
||||||
*.exe
|
|
||||||
*.dll
|
|
||||||
*.pdb
|
|
||||||
+31
-18
@@ -1,30 +1,43 @@
|
|||||||
cmake_minimum_required(VERSION 3.16)
|
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 17)
|
||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
set(CMAKE_AUTOMOC ON)
|
set(CMAKE_AUTOMOC ON)
|
||||||
set(CMAKE_AUTORCC ON)
|
set(CMAKE_AUTOUIC OFF)
|
||||||
set(CMAKE_AUTOUIC ON)
|
set(CMAKE_AUTORCC OFF)
|
||||||
|
|
||||||
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets)
|
find_package(OpenCV REQUIRED COMPONENTS core imgproc imgcodecs)
|
||||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)
|
|
||||||
find_package(OpenCV REQUIRED)
|
|
||||||
|
|
||||||
add_executable(QtOpenCVImageTool WIN32
|
find_package(Qt6 QUIET COMPONENTS Widgets)
|
||||||
|
if (Qt6_FOUND)
|
||||||
|
qt_add_executable(chengnan
|
||||||
main.cpp
|
main.cpp
|
||||||
MainWindow.h
|
MainWindow.h
|
||||||
MainWindow.cpp
|
MainWindow.cpp
|
||||||
)
|
)
|
||||||
|
target_link_libraries(chengnan PRIVATE Qt6::Widgets ${OpenCV_LIBS})
|
||||||
target_link_libraries(QtOpenCVImageTool PRIVATE
|
else()
|
||||||
Qt${QT_VERSION_MAJOR}::Widgets
|
find_package(Qt5 REQUIRED COMPONENTS Widgets)
|
||||||
${OpenCV_LIBS}
|
add_executable(chengnan
|
||||||
)
|
main.cpp
|
||||||
|
MainWindow.h
|
||||||
target_include_directories(QtOpenCVImageTool PRIVATE ${OpenCV_INCLUDE_DIRS})
|
MainWindow.cpp
|
||||||
|
)
|
||||||
if(QT_VERSION_MAJOR EQUAL 6)
|
target_link_libraries(chengnan PRIVATE Qt5::Widgets ${OpenCV_LIBS})
|
||||||
qt_finalize_executable(QtOpenCVImageTool)
|
|
||||||
endif()
|
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)
|
||||||
|
|||||||
+475
-300
@@ -1,433 +1,608 @@
|
|||||||
#include "MainWindow.h"
|
#include "MainWindow.h"
|
||||||
|
|
||||||
#include <QCheckBox>
|
#include <QAction>
|
||||||
|
#include <QApplication>
|
||||||
#include <QFileDialog>
|
#include <QFileDialog>
|
||||||
#include <QFileInfo>
|
#include <QFileInfo>
|
||||||
#include <QGroupBox>
|
#include <QImageReader>
|
||||||
#include <QHBoxLayout>
|
#include <QImageWriter>
|
||||||
#include <QImage>
|
#include <QKeySequence>
|
||||||
#include <QLabel>
|
#include <QMenuBar>
|
||||||
#include <QMessageBox>
|
#include <QMessageBox>
|
||||||
#include <QPushButton>
|
#include <QMouseEvent>
|
||||||
#include <QPixmap>
|
#include <QScrollBar>
|
||||||
#include <QScrollArea>
|
|
||||||
#include <QSlider>
|
#include <QSlider>
|
||||||
|
#include <QSplitter>
|
||||||
#include <QStatusBar>
|
#include <QStatusBar>
|
||||||
#include <QThread>
|
#include <QThread>
|
||||||
#include <QVBoxLayout>
|
#include <QToolBar>
|
||||||
|
#include <QTransform>
|
||||||
|
|
||||||
|
#include <opencv2/imgproc.hpp>
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <cmath>
|
#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)
|
QImage matToQImage(const cv::Mat &mat)
|
||||||
{
|
{
|
||||||
if (mat.empty()) {
|
if (mat.empty()) {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
cv::Mat rgb;
|
cv::Mat rgba;
|
||||||
if (mat.channels() == 1) {
|
if (mat.channels() == 1) {
|
||||||
cv::cvtColor(mat, rgb, cv::COLOR_GRAY2RGB);
|
cv::cvtColor(mat, rgba, cv::COLOR_GRAY2RGBA);
|
||||||
} else if (mat.channels() == 3) {
|
} else if (mat.channels() == 3) {
|
||||||
cv::cvtColor(mat, rgb, cv::COLOR_BGR2RGB);
|
cv::cvtColor(mat, rgba, cv::COLOR_BGR2RGBA);
|
||||||
} else if (mat.channels() == 4) {
|
|
||||||
cv::cvtColor(mat, rgb, cv::COLOR_BGRA2RGBA);
|
|
||||||
} else {
|
} else {
|
||||||
return {};
|
cv::cvtColor(mat, rgba, cv::COLOR_BGRA2RGBA);
|
||||||
}
|
}
|
||||||
|
|
||||||
const QImage::Format format = rgb.channels() == 4 ? QImage::Format_RGBA8888 : QImage::Format_RGB888;
|
return QImage(rgba.data, rgba.cols, rgba.rows, static_cast<int>(rgba.step), QImage::Format_RGBA8888).copy();
|
||||||
return QImage(rgb.data, rgb.cols, rgb.rows, static_cast<int>(rgb.step), format).copy();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
cv::Mat rotateWithBounds(const cv::Mat &image, double angle)
|
QImage extractObjectImage(const QImage &image)
|
||||||
{
|
{
|
||||||
if (image.empty() || std::abs(angle) < 0.01) {
|
const cv::Mat rgba = qImageToMat(image);
|
||||||
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 {};
|
|
||||||
}
|
|
||||||
|
|
||||||
cv::Mat gray;
|
cv::Mat gray;
|
||||||
cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
|
cv::cvtColor(rgba, gray, cv::COLOR_RGBA2GRAY);
|
||||||
cv::GaussianBlur(gray, gray, cv::Size(5, 5), 0);
|
cv::GaussianBlur(gray, gray, cv::Size(5, 5), 0.0);
|
||||||
|
|
||||||
cv::Mat binary;
|
cv::Mat edges;
|
||||||
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
|
cv::Canny(gray, edges, 60, 160);
|
||||||
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;
|
std::vector<std::vector<cv::Point>> contours;
|
||||||
cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
|
cv::findContours(edges, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
|
||||||
|
|
||||||
cv::Mat extracted = cv::Mat::zeros(image.size(), image.type());
|
|
||||||
image.copyTo(extracted, binary);
|
|
||||||
|
|
||||||
|
cv::Mat output = rgba.clone();
|
||||||
|
cv::cvtColor(output, output, cv::COLOR_RGBA2BGRA);
|
||||||
|
int count = 0;
|
||||||
for (const auto &contour : contours) {
|
for (const auto &contour : contours) {
|
||||||
const double area = cv::contourArea(contour);
|
const double area = cv::contourArea(contour);
|
||||||
if (area < 300.0) {
|
if (area < 120.0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
const cv::Rect rect = cv::boundingRect(contour);
|
||||||
++targetCount;
|
cv::rectangle(output, rect, cv::Scalar(0, 0, 255, 255), 2);
|
||||||
cv::rectangle(extracted, cv::boundingRect(contour), cv::Scalar(0, 255, 0), 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()) {
|
const cv::Mat rgba = qImageToMat(image);
|
||||||
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::Mat gray;
|
||||||
cv::cvtColor(output, gray, cv::COLOR_BGR2GRAY);
|
cv::cvtColor(rgba, gray, cv::COLOR_RGBA2GRAY);
|
||||||
cv::Mat binary;
|
|
||||||
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
|
cv::Mat edges;
|
||||||
std::vector<std::vector<cv::Point>> contours;
|
cv::Canny(gray, edges, 80, 180);
|
||||||
cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
|
const double brightness = cv::mean(gray)[0];
|
||||||
targetCount = static_cast<int>(std::count_if(contours.begin(), contours.end(), [](const auto &contour) {
|
const double edgeRatio = static_cast<double>(cv::countNonZero(edges)) / static_cast<double>(gray.total());
|
||||||
return cv::contourArea(contour) >= 300.0;
|
|
||||||
}));
|
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";
|
||||||
}
|
}
|
||||||
|
|
||||||
const QString classText = params.classifyImage ? classifyImage(output, targetCount) : QStringLiteral("处理完成");
|
cv::Mat output = rgba.clone();
|
||||||
emit processed(output, classText);
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
signals:
|
} // namespace
|
||||||
void processed(const cv::Mat &image, const QString &classText);
|
|
||||||
};
|
ImageLabel::ImageLabel(QWidget *parent)
|
||||||
|
: QLabel(parent)
|
||||||
|
{
|
||||||
|
setAlignment(Qt::AlignCenter);
|
||||||
|
setBackgroundRole(QPalette::Base);
|
||||||
|
setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
|
||||||
|
setScaledContents(false);
|
||||||
|
setMinimumSize(320, 240);
|
||||||
|
setText(tr("打开一张图片开始查看"));
|
||||||
|
}
|
||||||
|
|
||||||
|
void ImageLabel::mouseDoubleClickEvent(QMouseEvent *event)
|
||||||
|
{
|
||||||
|
if (event->button() == Qt::LeftButton) {
|
||||||
|
Q_EMIT doubleClicked();
|
||||||
|
}
|
||||||
|
QLabel::mouseDoubleClickEvent(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
MainWindow::MainWindow(QWidget *parent)
|
MainWindow::MainWindow(QWidget *parent)
|
||||||
: QMainWindow(parent)
|
: QMainWindow(parent)
|
||||||
{
|
{
|
||||||
qRegisterMetaType<cv::Mat>("cv::Mat");
|
createActions();
|
||||||
qRegisterMetaType<ProcessParams>("ProcessParams");
|
createMenus();
|
||||||
|
createToolbar();
|
||||||
|
createCentralWidget();
|
||||||
|
updateActions();
|
||||||
|
|
||||||
buildUi();
|
setWindowTitle(tr("chengnan 图片处理工具"));
|
||||||
|
resize(1200, 720);
|
||||||
auto *worker = new ImageProcessorWorker;
|
statusBar()->showMessage(tr("就绪"));
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
MainWindow::~MainWindow()
|
void MainWindow::createActions()
|
||||||
{
|
{
|
||||||
if (workerThread) {
|
openAction_ = new QAction(tr("打开(&O)"), this);
|
||||||
workerThread->quit();
|
openAction_->setShortcut(QKeySequence::Open);
|
||||||
workerThread->wait();
|
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);
|
QMenu *viewMenu = menuBar()->addMenu(tr("查看(&V)"));
|
||||||
auto *rootLayout = new QVBoxLayout(central);
|
viewMenu->addAction(zoomInAction_);
|
||||||
|
viewMenu->addAction(zoomOutAction_);
|
||||||
|
viewMenu->addAction(fitAction_);
|
||||||
|
viewMenu->addAction(resetAction_);
|
||||||
|
|
||||||
auto *buttonLayout = new QHBoxLayout;
|
QMenu *processMenu = menuBar()->addMenu(tr("处理(&P)"));
|
||||||
openButton = new QPushButton(QStringLiteral("打开图片"));
|
processMenu->addAction(rotateLeftAction_);
|
||||||
saveButton = new QPushButton(QStringLiteral("保存图片"));
|
processMenu->addAction(rotateRightAction_);
|
||||||
saveAsButton = new QPushButton(QStringLiteral("另存图片"));
|
processMenu->addAction(flipHorizontalAction_);
|
||||||
resetButton = new QPushButton(QStringLiteral("重置处理"));
|
processMenu->addAction(flipVerticalAction_);
|
||||||
buttonLayout->addWidget(openButton);
|
processMenu->addSeparator();
|
||||||
buttonLayout->addWidget(saveButton);
|
processMenu->addAction(grayscaleAction_);
|
||||||
buttonLayout->addWidget(saveAsButton);
|
processMenu->addAction(invertAction_);
|
||||||
buttonLayout->addStretch();
|
processMenu->addSeparator();
|
||||||
buttonLayout->addWidget(resetButton);
|
processMenu->addAction(extractAction_);
|
||||||
|
processMenu->addAction(classifyAction_);
|
||||||
|
}
|
||||||
|
|
||||||
auto *controlBox = new QGroupBox(QStringLiteral("图像处理"));
|
void MainWindow::createToolbar()
|
||||||
auto *controlLayout = new QHBoxLayout(controlBox);
|
{
|
||||||
|
QToolBar *toolbar = addToolBar(tr("主工具栏"));
|
||||||
|
toolbar->setMovable(false);
|
||||||
|
toolbar->addAction(openAction_);
|
||||||
|
toolbar->addAction(saveAction_);
|
||||||
|
toolbar->addSeparator();
|
||||||
|
toolbar->addAction(zoomOutAction_);
|
||||||
|
|
||||||
scaleSlider = new QSlider(Qt::Horizontal);
|
zoomSlider_ = new QSlider(Qt::Horizontal, this);
|
||||||
scaleSlider->setRange(25, 200);
|
zoomSlider_->setRange(10, 400);
|
||||||
scaleSlider->setValue(100);
|
zoomSlider_->setValue(100);
|
||||||
rotateSlider = new QSlider(Qt::Horizontal);
|
zoomSlider_->setFixedWidth(180);
|
||||||
rotateSlider->setRange(-180, 180);
|
zoomSlider_->setToolTip(tr("缩放比例"));
|
||||||
translateXSlider = new QSlider(Qt::Horizontal);
|
connect(zoomSlider_, &QSlider::valueChanged, this, &MainWindow::updateZoomFromSlider);
|
||||||
translateXSlider->setRange(-200, 200);
|
toolbar->addWidget(zoomSlider_);
|
||||||
translateYSlider = new QSlider(Qt::Horizontal);
|
|
||||||
translateYSlider->setRange(-200, 200);
|
|
||||||
extractCheckBox = new QCheckBox(QStringLiteral("目标提取"));
|
|
||||||
classifyCheckBox = new QCheckBox(QStringLiteral("图像分类"));
|
|
||||||
|
|
||||||
auto addSlider = [controlLayout](const QString &name, QSlider *slider) {
|
toolbar->addAction(zoomInAction_);
|
||||||
auto *box = new QWidget;
|
toolbar->addAction(fitAction_);
|
||||||
auto *layout = new QVBoxLayout(box);
|
toolbar->addSeparator();
|
||||||
layout->setContentsMargins(0, 0, 0, 0);
|
toolbar->addAction(rotateLeftAction_);
|
||||||
layout->addWidget(new QLabel(name));
|
toolbar->addAction(rotateRightAction_);
|
||||||
layout->addWidget(slider);
|
toolbar->addAction(grayscaleAction_);
|
||||||
controlLayout->addWidget(box, 1);
|
toolbar->addAction(invertAction_);
|
||||||
};
|
toolbar->addAction(extractAction_);
|
||||||
|
toolbar->addAction(classifyAction_);
|
||||||
|
}
|
||||||
|
|
||||||
addSlider(QStringLiteral("缩放"), scaleSlider);
|
void MainWindow::createCentralWidget()
|
||||||
addSlider(QStringLiteral("旋转"), rotateSlider);
|
{
|
||||||
addSlider(QStringLiteral("水平平移"), translateXSlider);
|
originalLabel_ = new ImageLabel(this);
|
||||||
addSlider(QStringLiteral("垂直平移"), translateYSlider);
|
processedLabel_ = new ImageLabel(this);
|
||||||
controlLayout->addWidget(extractCheckBox);
|
originalLabel_->setText(tr("处理前图像"));
|
||||||
controlLayout->addWidget(classifyCheckBox);
|
processedLabel_->setText(tr("处理后图像"));
|
||||||
|
connect(originalLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow);
|
||||||
|
connect(processedLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow);
|
||||||
|
|
||||||
auto *imageLayout = new QHBoxLayout;
|
originalScrollArea_ = new QScrollArea(this);
|
||||||
originalLabel = new QLabel(QStringLiteral("原图"));
|
originalScrollArea_->setBackgroundRole(QPalette::Dark);
|
||||||
resultLabel = new QLabel(QStringLiteral("处理后图像"));
|
originalScrollArea_->setWidget(originalLabel_);
|
||||||
originalLabel->setAlignment(Qt::AlignCenter);
|
originalScrollArea_->setWidgetResizable(true);
|
||||||
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;
|
processedScrollArea_ = new QScrollArea(this);
|
||||||
auto *resultScroll = new QScrollArea;
|
processedScrollArea_->setBackgroundRole(QPalette::Dark);
|
||||||
originalScroll->setWidget(originalLabel);
|
processedScrollArea_->setWidget(processedLabel_);
|
||||||
resultScroll->setWidget(resultLabel);
|
processedScrollArea_->setWidgetResizable(true);
|
||||||
originalScroll->setWidgetResizable(true);
|
|
||||||
resultScroll->setWidgetResizable(true);
|
|
||||||
|
|
||||||
imageLayout->addWidget(originalScroll, 1);
|
auto *splitter = new QSplitter(Qt::Horizontal, this);
|
||||||
imageLayout->addWidget(resultScroll, 1);
|
splitter->addWidget(originalScrollArea_);
|
||||||
|
splitter->addWidget(processedScrollArea_);
|
||||||
rootLayout->addLayout(buttonLayout);
|
splitter->setStretchFactor(0, 1);
|
||||||
rootLayout->addWidget(controlBox);
|
splitter->setStretchFactor(1, 1);
|
||||||
rootLayout->addLayout(imageLayout, 1);
|
setCentralWidget(splitter);
|
||||||
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()
|
void MainWindow::openImage()
|
||||||
{
|
{
|
||||||
const QString fileName = QFileDialog::getOpenFileName(
|
const QString fileName = QFileDialog::getOpenFileName(
|
||||||
this,
|
this,
|
||||||
QStringLiteral("打开图片"),
|
tr("打开图片"),
|
||||||
QString(),
|
QString(),
|
||||||
QStringLiteral("Images (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)"));
|
tr("图片文件 (*.png *.jpg *.jpeg *.bmp *.gif *.webp);;所有文件 (*.*)"));
|
||||||
|
|
||||||
if (fileName.isEmpty()) {
|
if (fileName.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
originalImage = cv::imread(fileName.toLocal8Bit().constData(), cv::IMREAD_COLOR);
|
QImageReader reader(fileName);
|
||||||
if (originalImage.empty()) {
|
reader.setAutoTransform(true);
|
||||||
QMessageBox::warning(this, QStringLiteral("打开失败"), QStringLiteral("无法读取该图片文件。"));
|
const QImage image = reader.read();
|
||||||
|
if (image.isNull()) {
|
||||||
|
QMessageBox::warning(this, tr("打开失败"), tr("无法读取图片:%1").arg(reader.errorString()));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
savePath.clear();
|
setImage(image, fileName);
|
||||||
updateOriginalView();
|
|
||||||
scheduleProcessing();
|
|
||||||
statusLabel->setText(QStringLiteral("已打开:%1").arg(QFileInfo(fileName).fileName()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void MainWindow::saveImage()
|
void MainWindow::saveImage()
|
||||||
{
|
{
|
||||||
if (savePath.isEmpty()) {
|
if (!ensureImageLoaded(tr("保存"))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentPath_.isEmpty()) {
|
||||||
saveImageAs();
|
saveImageAs();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (writeResultToFile(savePath)) {
|
writeImageToPath(currentPath_);
|
||||||
statusLabel->setText(QStringLiteral("已保存:%1").arg(QFileInfo(savePath).fileName()));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void MainWindow::saveImageAs()
|
void MainWindow::saveImageAs()
|
||||||
{
|
{
|
||||||
if (resultImage.empty()) {
|
if (!ensureImageLoaded(tr("另存为"))) {
|
||||||
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("请先打开并处理图片。"));
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const QString fileName = QFileDialog::getSaveFileName(
|
const QString fileName = QFileDialog::getSaveFileName(
|
||||||
this,
|
this,
|
||||||
QStringLiteral("另存图片"),
|
tr("另存为"),
|
||||||
QStringLiteral("processed.png"),
|
currentPath_.isEmpty() ? QStringLiteral("chengnan.png") : currentPath_,
|
||||||
QStringLiteral("PNG (*.png);;JPEG (*.jpg *.jpeg);;BMP (*.bmp);;TIFF (*.tif *.tiff)"));
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (writeResultToFile(fileName)) {
|
const QSize viewportSize = processedScrollArea_->viewport()->size();
|
||||||
savePath = fileName;
|
const QSize imageSize = currentImage_.size();
|
||||||
statusLabel->setText(QStringLiteral("已另存为:%1").arg(QFileInfo(fileName).fileName()));
|
if (imageSize.isEmpty()) {
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
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();
|
setZoomFactor(1.0);
|
||||||
updateResultView();
|
|
||||||
statusLabel->setText(classText);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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 (!ensureImageLoaded(tr("翻转"))) {
|
||||||
if (image.isNull()) {
|
return;
|
||||||
label->setText(QStringLiteral("无图像"));
|
}
|
||||||
|
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;
|
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;
|
const QSize scaledSize(
|
||||||
params.scale = scaleSlider->value() / 100.0;
|
std::max(1, static_cast<int>(std::round(image.width() * zoomFactor_))),
|
||||||
params.angle = rotateSlider->value();
|
std::max(1, static_cast<int>(std::round(image.height() * zoomFactor_))));
|
||||||
params.translateX = translateXSlider->value();
|
const QPixmap pixmap = QPixmap::fromImage(image).scaled(
|
||||||
params.translateY = translateYSlider->value();
|
scaledSize,
|
||||||
params.extractTarget = extractCheckBox->isChecked();
|
Qt::KeepAspectRatio,
|
||||||
params.classifyImage = classifyCheckBox->isChecked();
|
Qt::SmoothTransformation);
|
||||||
return params;
|
|
||||||
|
label->setText(QString());
|
||||||
|
label->setPixmap(pixmap);
|
||||||
|
label->resize(pixmap.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
bool MainWindow::writeResultToFile(const QString &fileName)
|
void MainWindow::setZoomFactor(double factor)
|
||||||
{
|
{
|
||||||
if (resultImage.empty()) {
|
zoomFactor_ = std::clamp(factor, 0.10, 4.00);
|
||||||
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("没有可保存的处理结果。"));
|
updateImageView();
|
||||||
return false;
|
}
|
||||||
|
|
||||||
|
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::information(nullptr, actionName, tr("请先打开一张图片。"));
|
||||||
QMessageBox::warning(this, QStringLiteral("保存失败"), QStringLiteral("无法写入该图片文件。"));
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
currentPath_ = path;
|
||||||
|
setWindowTitle(tr("%1 - chengnan 图片处理工具").arg(QFileInfo(path).fileName()));
|
||||||
|
statusBar()->showMessage(tr("已保存:%1").arg(path), 5000);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
#include "MainWindow.moc"
|
|
||||||
|
|||||||
+73
-49
@@ -1,76 +1,100 @@
|
|||||||
#ifndef MAINWINDOW_H
|
#ifndef MAINWINDOW_H
|
||||||
#define MAINWINDOW_H
|
#define MAINWINDOW_H
|
||||||
|
|
||||||
|
#include <QImage>
|
||||||
|
#include <QLabel>
|
||||||
#include <QMainWindow>
|
#include <QMainWindow>
|
||||||
#include <QMetaType>
|
#include <QPixmap>
|
||||||
|
#include <QScrollArea>
|
||||||
|
#include <QString>
|
||||||
|
#include <functional>
|
||||||
|
|
||||||
#include <opencv2/opencv.hpp>
|
class QAction;
|
||||||
|
class QMenu;
|
||||||
class QLabel;
|
|
||||||
class QPushButton;
|
class QPushButton;
|
||||||
class QSlider;
|
class QSlider;
|
||||||
class QCheckBox;
|
|
||||||
class QThread;
|
|
||||||
|
|
||||||
struct ProcessParams
|
class ImageLabel final : public QLabel
|
||||||
{
|
{
|
||||||
double scale = 1.0;
|
Q_OBJECT
|
||||||
int translateX = 0;
|
|
||||||
int translateY = 0;
|
public:
|
||||||
double angle = 0.0;
|
explicit ImageLabel(QWidget *parent = nullptr);
|
||||||
bool extractTarget = false;
|
|
||||||
bool classifyImage = false;
|
Q_SIGNALS:
|
||||||
|
void doubleClicked();
|
||||||
|
|
||||||
|
protected:
|
||||||
|
void mouseDoubleClickEvent(QMouseEvent *event) override;
|
||||||
};
|
};
|
||||||
|
|
||||||
Q_DECLARE_METATYPE(cv::Mat)
|
class MainWindow final : public QMainWindow
|
||||||
Q_DECLARE_METATYPE(ProcessParams)
|
|
||||||
|
|
||||||
class MainWindow : public QMainWindow
|
|
||||||
{
|
{
|
||||||
Q_OBJECT
|
Q_OBJECT
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit MainWindow(QWidget *parent = nullptr);
|
explicit MainWindow(QWidget *parent = nullptr);
|
||||||
~MainWindow() override;
|
|
||||||
|
|
||||||
signals:
|
private Q_SLOTS:
|
||||||
void processRequested(const cv::Mat &image, const ProcessParams ¶ms);
|
|
||||||
|
|
||||||
private slots:
|
|
||||||
void openImage();
|
void openImage();
|
||||||
void saveImage();
|
void saveImage();
|
||||||
void saveImageAs();
|
void saveImageAs();
|
||||||
void resetParams();
|
void zoomIn();
|
||||||
void scheduleProcessing();
|
void zoomOut();
|
||||||
void onProcessed(const cv::Mat &image, const QString &classText);
|
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:
|
private:
|
||||||
void buildUi();
|
void createActions();
|
||||||
void updateOriginalView();
|
void createMenus();
|
||||||
void updateResultView();
|
void createToolbar();
|
||||||
void setImageOnLabel(QLabel *label, const cv::Mat &mat);
|
void createCentralWidget();
|
||||||
ProcessParams currentParams() const;
|
void setImage(const QImage &image, const QString &path = QString());
|
||||||
bool writeResultToFile(const QString &fileName);
|
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;
|
ImageLabel *originalLabel_ = nullptr;
|
||||||
QLabel *resultLabel = nullptr;
|
ImageLabel *processedLabel_ = nullptr;
|
||||||
QLabel *statusLabel = nullptr;
|
QScrollArea *originalScrollArea_ = nullptr;
|
||||||
QPushButton *openButton = nullptr;
|
QScrollArea *processedScrollArea_ = nullptr;
|
||||||
QPushButton *saveButton = nullptr;
|
QSlider *zoomSlider_ = 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;
|
|
||||||
|
|
||||||
cv::Mat originalImage;
|
QImage originalImage_;
|
||||||
cv::Mat resultImage;
|
QImage currentImage_;
|
||||||
QString savePath;
|
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.
@@ -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
|
|
||||||
@@ -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/."
|
|
||||||
@@ -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)
|
|
||||||
@@ -5,10 +5,12 @@
|
|||||||
int main(int argc, char *argv[])
|
int main(int argc, char *argv[])
|
||||||
{
|
{
|
||||||
QApplication app(argc, argv);
|
QApplication app(argc, argv);
|
||||||
|
QApplication::setApplicationName(QStringLiteral("chengnan"));
|
||||||
|
QApplication::setApplicationVersion(QStringLiteral(CHENGNAN_APP_VERSION));
|
||||||
|
QApplication::setOrganizationName(QStringLiteral("luochen570"));
|
||||||
|
|
||||||
MainWindow window;
|
MainWindow window;
|
||||||
window.resize(1180, 760);
|
|
||||||
window.show();
|
window.show();
|
||||||
|
|
||||||
return app.exec();
|
return QApplication::exec();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,259 +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`:主窗口类和处理参数声明。
|
- 使用 Qt 设计界面:已使用 Qt Widgets 实现菜单栏、工具栏和双栏图像显示界面。
|
||||||
- `MainWindow.cpp`:界面、图像读写、Qt 线程和 OpenCV 处理实现。
|
- 打开图片、保存图片、另存图片:已实现。
|
||||||
|
- 缩放、平移、旋转:
|
||||||
|
- 缩放:工具栏滑块、放大、缩小、原始大小、双击适配窗口。
|
||||||
|
- 平移:图片位于 `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
|
```text
|
||||||
Desktop development with C++
|
chengnan/
|
||||||
MSVC v143 x64/x86 build tools
|
├── .gitea/workflows/build-windows-release.yml
|
||||||
Windows 10 SDK 或 Windows 11 SDK
|
├── CMakeLists.txt
|
||||||
C++ CMake tools for Windows
|
├── 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
|
```text
|
||||||
C:\Program Files\Microsoft Visual Studio\2022\Community
|
C:\Qt\6.7.3\msvc2022_64
|
||||||
C:\Program Files\Microsoft Visual Studio\2022\BuildTools
|
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Qt for Windows
|
不要写成:
|
||||||
|
|
||||||
使用 Qt Online Installer 安装 Qt。推荐安装 Qt 6.x,并勾选 MSVC 64 位组件,例如:
|
|
||||||
|
|
||||||
```text
|
```text
|
||||||
Qt 6.6.x
|
C:\Qt
|
||||||
MSVC 2019 64-bit 或 MSVC 2022 64-bit
|
|
||||||
Qt Creator
|
|
||||||
```
|
```
|
||||||
|
|
||||||
安装完成后,Qt 路径通常类似:
|
### 找不到 OpenCV
|
||||||
|
|
||||||
|
确认 CMake 的 `CMAKE_PREFIX_PATH` 包含 OpenCV 的 `build` 目录。例如:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
C:\Qt\6.6.0\msvc2019_64
|
C:\opencv\build
|
||||||
C:\Qt\6.6.0\msvc2022_64
|
|
||||||
```
|
```
|
||||||
|
|
||||||
该目录下应存在:
|
该目录下通常能找到 `OpenCVConfig.cmake`。
|
||||||
|
|
||||||
```text
|
### 找不到 MSVC 编译器
|
||||||
C:\Qt\6.6.0\msvc2019_64\lib\cmake\Qt6\Qt6Config.cmake
|
|
||||||
```
|
|
||||||
|
|
||||||
3. OpenCV for Windows
|
请安装 Visual Studio 2022 的 `使用 C++ 的桌面开发`,然后在 “x64 Native Tools Command Prompt for VS 2022” 或已配置 VS 环境的 PowerShell 里运行构建命令。
|
||||||
|
|
||||||
可以使用 OpenCV 官方 Windows 包。解压或安装到例如:
|
### exe 复制到其它电脑无法运行
|
||||||
|
|
||||||
```text
|
不要只复制单个 `chengnan.exe`。需要同时复制 Qt / OpenCV DLL 和 Qt 插件目录,或直接使用 Gitea Actions 发布的 zip 附件。
|
||||||
C:\opencv
|
|
||||||
```
|
|
||||||
|
|
||||||
常见的 CMake 配置路径是:
|
## 开发说明
|
||||||
|
|
||||||
```text
|
- `main.cpp`:应用入口,创建并显示主窗口
|
||||||
C:\opencv\build\x64\vc16\lib
|
- `MainWindow.h`:主窗口和图片标签类声明
|
||||||
```
|
- `MainWindow.cpp`:菜单、工具栏、图片显示、OpenCV 图像处理和 Qt 线程逻辑
|
||||||
|
- `CMakeLists.txt`:Qt Widgets + OpenCV CMake 构建配置
|
||||||
该目录下应存在:
|
- `readme.md`:项目说明文档
|
||||||
|
|
||||||
```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