Compare commits
22
Commits
main
..
796a2b7712
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,184 @@
|
||||
name: Cross Build Windows Release on Linux
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- 'v*'
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
cross-build-windows:
|
||||
# Gitea act_runner 标签为 9950x;该工作流在 Linux Runner 中交叉编译 Windows x86_64 包。
|
||||
runs-on: 9950x
|
||||
container:
|
||||
image: fedora:latest
|
||||
|
||||
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.tuna.tsinghua.edu.cn/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 makecache --refresh -y
|
||||
|
||||
- name: Checkout
|
||||
run: |
|
||||
set -euo pipefail
|
||||
dnf install -y git rsync
|
||||
WORKDIR="$(pwd)"
|
||||
SRC_DIR="$(mktemp -d /tmp/chengnan-source.XXXXXX)"
|
||||
REPO_URL="${GITHUB_SERVER_URL:-https://git.luochen570.cn}/${GITHUB_REPOSITORY}.git"
|
||||
TOKEN="${GITHUB_TOKEN:-}"
|
||||
if [ -n "$TOKEN" ]; then
|
||||
git -c http.extraHeader="Authorization: token ${TOKEN}" \
|
||||
clone --depth 1 --branch "${GITHUB_REF_NAME:-main}" "$REPO_URL" "$SRC_DIR"
|
||||
else
|
||||
git clone --depth 1 --branch "${GITHUB_REF_NAME:-main}" "$REPO_URL" "$SRC_DIR"
|
||||
fi
|
||||
rsync -a --delete "$SRC_DIR/" "$WORKDIR/"
|
||||
rm -rf "$SRC_DIR"
|
||||
|
||||
- name: Install cross build dependencies
|
||||
run: |
|
||||
set -euo pipefail
|
||||
dnf install -y \
|
||||
cmake \
|
||||
curl \
|
||||
ninja-build \
|
||||
p7zip \
|
||||
p7zip-plugins \
|
||||
mingw64-gcc-c++ \
|
||||
mingw64-qt6-qtbase \
|
||||
mingw64-opencv
|
||||
|
||||
- name: Configure
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cmake -S . -B build-windows-cross -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_TOOLCHAIN_FILE=/usr/share/mingw/toolchain-mingw64.cmake
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cmake --build build-windows-cross --parallel "$(nproc)"
|
||||
|
||||
- name: Package
|
||||
run: |
|
||||
set -euo pipefail
|
||||
APP_NAME="chengnan"
|
||||
PACKAGE_NAME="chengnan-windows-x86_64-cross"
|
||||
PACKAGE_DIR="dist-windows-cross/${PACKAGE_NAME}"
|
||||
EXE="build-windows-cross/${APP_NAME}.exe"
|
||||
|
||||
test -f "$EXE"
|
||||
rm -rf dist-windows-cross
|
||||
mkdir -p "$PACKAGE_DIR"
|
||||
cp "$EXE" "$PACKAGE_DIR/"
|
||||
|
||||
# 收集 MinGW 运行时、Qt、OpenCV 依赖 DLL。
|
||||
for round in 1 2 3; do
|
||||
while IFS= read -r binary; do
|
||||
while IFS= read -r dll; do
|
||||
[ -f "$dll" ] || continue
|
||||
cp -n "$dll" "$PACKAGE_DIR/" || true
|
||||
done < <(x86_64-w64-mingw32-objdump -p "$binary" \
|
||||
| awk '/DLL Name:/ {print $3}' \
|
||||
| while read -r name; do \
|
||||
find /usr/x86_64-w64-mingw32/sys-root/mingw/bin -iname "$name" -print -quit; \
|
||||
done)
|
||||
done < <(find "$PACKAGE_DIR" -maxdepth 1 -type f \( -name '*.exe' -o -name '*.dll' \) | sort)
|
||||
done
|
||||
|
||||
# Qt 平台插件是 Windows Qt GUI 程序启动所必需的。
|
||||
QT_PLUGIN_ROOT="/usr/x86_64-w64-mingw32/sys-root/mingw/lib/qt6/plugins"
|
||||
if [ -d "$QT_PLUGIN_ROOT/platforms" ]; then
|
||||
mkdir -p "$PACKAGE_DIR/platforms"
|
||||
cp -n "$QT_PLUGIN_ROOT/platforms"/*.dll "$PACKAGE_DIR/platforms/"
|
||||
fi
|
||||
|
||||
cat > "$PACKAGE_DIR/README.txt" <<'EOF'
|
||||
chengnan Windows x86_64 交叉编译发布包
|
||||
|
||||
运行方式:
|
||||
1. 解压整个目录。
|
||||
2. 双击 chengnan.exe 运行。
|
||||
|
||||
说明:
|
||||
- 本目录由 Linux Runner 使用 MinGW-w64 交叉编译生成。
|
||||
- 请不要只复制 chengnan.exe,需保留同目录 DLL 和 platforms 子目录。
|
||||
EOF
|
||||
|
||||
(cd dist-windows-cross && 7z a -tzip "${PACKAGE_NAME}.zip" "${PACKAGE_NAME}" >/dev/null)
|
||||
(cd dist-windows-cross && sha256sum "${PACKAGE_NAME}.zip" > "${PACKAGE_NAME}.zip.sha256")
|
||||
|
||||
# 当前 Gitea 上传入口约 60 秒会返回 502;大文件按 15 MiB 分片上传。
|
||||
ZIP="dist-windows-cross/${PACKAGE_NAME}.zip"
|
||||
split -b 15M -d -a 3 "$ZIP" "${ZIP}.part-"
|
||||
(cd dist-windows-cross && sha256sum "${PACKAGE_NAME}.zip".part-* > "${PACKAGE_NAME}.zip.parts.sha256")
|
||||
du -h "$ZIP" "${ZIP}".part-*
|
||||
|
||||
- name: Verify package
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -s dist-windows-cross/chengnan-windows-x86_64-cross.zip
|
||||
test -s dist-windows-cross/chengnan-windows-x86_64-cross.zip.part-000
|
||||
test -s dist-windows-cross/chengnan-windows-x86_64-cross.zip.parts.sha256
|
||||
(cd dist-windows-cross && sha256sum -c chengnan-windows-x86_64-cross.zip.sha256)
|
||||
(cd dist-windows-cross && sha256sum -c chengnan-windows-x86_64-cross.zip.parts.sha256)
|
||||
7z l dist-windows-cross/chengnan-windows-x86_64-cross.zip | grep 'chengnan.exe'
|
||||
7z l dist-windows-cross/chengnan-windows-x86_64-cross.zip | grep 'platforms/'
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
limit = 20 * 1024 * 1024
|
||||
for part in Path('dist-windows-cross').glob('chengnan-windows-x86_64-cross.zip.part-*'):
|
||||
size = part.stat().st_size
|
||||
print(part.name, size)
|
||||
if size > limit:
|
||||
raise SystemExit(f'{part} is too large for the current Gitea upload path')
|
||||
PY
|
||||
|
||||
- name: Upload package to Gitea Packages
|
||||
env:
|
||||
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
PACKAGE_NAME="chengnan-windows-x86_64-cross"
|
||||
VERSION="${GITHUB_SHA:-manual}"
|
||||
VERSION="${VERSION:0:10}"
|
||||
OWNER="${GITHUB_REPOSITORY%%/*}"
|
||||
API_BASE="${GITHUB_SERVER_URL:-https://git.luochen570.cn}/api/packages/${OWNER}/generic/chengnan/${VERSION}"
|
||||
TOKEN="${PACKAGE_TOKEN:-${GITHUB_TOKEN:-}}"
|
||||
test -n "$TOKEN"
|
||||
upload_file() {
|
||||
local src="$1"
|
||||
local url="$2"
|
||||
local status
|
||||
status="$(curl --show-error --silent --location \
|
||||
--header "Authorization: token ${TOKEN}" \
|
||||
--upload-file "$src" \
|
||||
--write-out '%{http_code}' \
|
||||
--output /tmp/gitea-upload-response.txt \
|
||||
"$url")"
|
||||
if [ "$status" != "201" ] && [ "$status" != "200" ]; then
|
||||
echo "Upload failed with HTTP ${status}: ${url}" >&2
|
||||
cat /tmp/gitea-upload-response.txt >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
for part in dist-windows-cross/${PACKAGE_NAME}.zip.part-*; do
|
||||
upload_file "$part" "${API_BASE}/$(basename "$part")"
|
||||
done
|
||||
upload_file "dist-windows-cross/${PACKAGE_NAME}.zip.sha256" "${API_BASE}/${PACKAGE_NAME}.zip.sha256"
|
||||
upload_file "dist-windows-cross/${PACKAGE_NAME}.zip.parts.sha256" "${API_BASE}/${PACKAGE_NAME}.zip.parts.sha256"
|
||||
echo "Package uploaded to: ${API_BASE}/"
|
||||
echo "Download all ${PACKAGE_NAME}.zip.part-* files, then reconstruct with: cat ${PACKAGE_NAME}.zip.part-* > ${PACKAGE_NAME}.zip"
|
||||
@@ -0,0 +1,180 @@
|
||||
name: Build Windows Release with MSYS2
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- 'v*'
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-windows-msys2:
|
||||
# 需要 Gitea act_runner 运行在 Windows,并且能访问 GitHub 以拉取 actions/checkout、msys2/setup-msys2、actions/upload-artifact。
|
||||
# 如果你的 runner 使用了自定义标签,可以在 Gitea runner 配置中给它同时加上 windows 标签。
|
||||
runs-on:
|
||||
- windows
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: msys2 {0}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup MSYS2 build environment
|
||||
uses: msys2/setup-msys2@v2
|
||||
with:
|
||||
msystem: UCRT64
|
||||
update: true
|
||||
install: >-
|
||||
git
|
||||
curl
|
||||
zip
|
||||
p7zip
|
||||
mingw-w64-ucrt-x86_64-toolchain
|
||||
mingw-w64-ucrt-x86_64-cmake
|
||||
mingw-w64-ucrt-x86_64-ninja
|
||||
mingw-w64-ucrt-x86_64-qt6-base
|
||||
mingw-w64-ucrt-x86_64-opencv
|
||||
|
||||
- name: Configure
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cmake -S . -B build-windows-msys2 -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_PREFIX_PATH=/ucrt64
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cmake --build build-windows-msys2 --parallel "$(nproc)"
|
||||
|
||||
- name: Package
|
||||
run: |
|
||||
set -euo pipefail
|
||||
APP_NAME="chengnan"
|
||||
PACKAGE_NAME="chengnan-windows-x86_64-msys2"
|
||||
PACKAGE_DIR="dist-windows-msys2/${PACKAGE_NAME}"
|
||||
EXE="build-windows-msys2/${APP_NAME}.exe"
|
||||
|
||||
test -f "$EXE"
|
||||
rm -rf dist-windows-msys2
|
||||
mkdir -p "$PACKAGE_DIR"
|
||||
cp "$EXE" "$PACKAGE_DIR/"
|
||||
|
||||
# 部署 Qt 运行时和插件。
|
||||
if command -v windeployqt >/dev/null 2>&1; then
|
||||
windeployqt --release --no-translations "$PACKAGE_DIR/${APP_NAME}.exe"
|
||||
elif command -v windeployqt6 >/dev/null 2>&1; then
|
||||
windeployqt6 --release --no-translations "$PACKAGE_DIR/${APP_NAME}.exe"
|
||||
else
|
||||
echo "windeployqt not found" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 收集 MinGW/MSYS2/OpenCV 运行时 DLL。ldd 会列出 exe/dll 依赖;循环几轮收集二级依赖。
|
||||
for round in 1 2 3; do
|
||||
while IFS= read -r binary; do
|
||||
while IFS= read -r dll; do
|
||||
[ -f "$dll" ] || continue
|
||||
cp -n "$dll" "$PACKAGE_DIR/" || true
|
||||
done < <(ldd "$binary" \
|
||||
| awk '/=> \/ucrt64\/bin\// {print $3} /^\/ucrt64\/bin\// {print $1}' \
|
||||
| sort -u)
|
||||
done < <(find "$PACKAGE_DIR" -maxdepth 2 -type f \( -name '*.exe' -o -name '*.dll' \) | sort)
|
||||
done
|
||||
|
||||
cat > "$PACKAGE_DIR/README.txt" <<'EOF'
|
||||
chengnan Windows x86_64 MSYS2 发布包
|
||||
|
||||
运行方式:
|
||||
1. 解压整个目录。
|
||||
2. 双击 chengnan.exe 运行。
|
||||
|
||||
说明:
|
||||
- 本目录由 Windows Runner 使用 MSYS2 UCRT64 构建生成。
|
||||
- 本目录已包含 Qt、OpenCV 和 MinGW 运行时 DLL。
|
||||
- 请不要只复制 chengnan.exe,需保留同目录 DLL 和 Qt plugins 子目录。
|
||||
EOF
|
||||
|
||||
(cd dist-windows-msys2 && 7z a -tzip "${PACKAGE_NAME}.zip" "${PACKAGE_NAME}" >/dev/null)
|
||||
(cd dist-windows-msys2 && sha256sum "${PACKAGE_NAME}.zip" > "${PACKAGE_NAME}.zip.sha256")
|
||||
|
||||
# 当前 Gitea 上传入口约 60 秒会返回 502;大文件按 15 MiB 分片上传。
|
||||
ZIP="dist-windows-msys2/${PACKAGE_NAME}.zip"
|
||||
split -b 15M -d -a 3 "$ZIP" "${ZIP}.part-"
|
||||
(cd dist-windows-msys2 && sha256sum "${PACKAGE_NAME}.zip".part-* > "${PACKAGE_NAME}.zip.parts.sha256")
|
||||
du -h "$ZIP" "${ZIP}".part-*
|
||||
|
||||
- name: Verify package
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -s dist-windows-msys2/chengnan-windows-x86_64-msys2.zip
|
||||
test -s dist-windows-msys2/chengnan-windows-x86_64-msys2.zip.part-000
|
||||
test -s dist-windows-msys2/chengnan-windows-x86_64-msys2.zip.sha256
|
||||
test -s dist-windows-msys2/chengnan-windows-x86_64-msys2.zip.parts.sha256
|
||||
(cd dist-windows-msys2 && sha256sum -c chengnan-windows-x86_64-msys2.zip.sha256)
|
||||
(cd dist-windows-msys2 && sha256sum -c chengnan-windows-x86_64-msys2.zip.parts.sha256)
|
||||
7z l dist-windows-msys2/chengnan-windows-x86_64-msys2.zip | grep 'chengnan.exe'
|
||||
limit=$((20 * 1024 * 1024))
|
||||
for part in dist-windows-msys2/chengnan-windows-x86_64-msys2.zip.part-*; do
|
||||
size="$(wc -c < "$part")"
|
||||
echo "$(basename "$part") $size"
|
||||
if [ "$size" -gt "$limit" ]; then
|
||||
echo "$part is too large for the current Gitea upload path" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: chengnan-windows-x86_64-msys2
|
||||
path: |
|
||||
dist-windows-msys2/chengnan-windows-x86_64-msys2.zip
|
||||
dist-windows-msys2/chengnan-windows-x86_64-msys2.zip.sha256
|
||||
dist-windows-msys2/chengnan-windows-x86_64-msys2.zip.part-*
|
||||
dist-windows-msys2/chengnan-windows-x86_64-msys2.zip.parts.sha256
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload package to Gitea Packages
|
||||
if: ${{ github.event_name != 'pull_request' }}
|
||||
env:
|
||||
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
PACKAGE_NAME="chengnan-windows-x86_64-msys2"
|
||||
VERSION="${GITHUB_SHA:-manual}"
|
||||
VERSION="${VERSION:0:10}"
|
||||
OWNER="${GITHUB_REPOSITORY%%/*}"
|
||||
API_BASE="${GITHUB_SERVER_URL:-https://git.luochen570.cn}/api/packages/${OWNER}/generic/chengnan/${VERSION}"
|
||||
TOKEN="${PACKAGE_TOKEN:-${GITHUB_TOKEN:-}}"
|
||||
test -n "$TOKEN"
|
||||
upload_file() {
|
||||
local src="$1"
|
||||
local url="$2"
|
||||
local status
|
||||
status="$(curl --show-error --silent --location \
|
||||
--header "Authorization: token ${TOKEN}" \
|
||||
--upload-file "$src" \
|
||||
--write-out '%{http_code}' \
|
||||
--output /tmp/gitea-upload-response.txt \
|
||||
"$url")"
|
||||
if [ "$status" != "201" ] && [ "$status" != "200" ]; then
|
||||
echo "Upload failed with HTTP ${status}: ${url}" >&2
|
||||
cat /tmp/gitea-upload-response.txt >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
for part in dist-windows-msys2/${PACKAGE_NAME}.zip.part-*; do
|
||||
upload_file "$part" "${API_BASE}/$(basename "$part")"
|
||||
done
|
||||
upload_file "dist-windows-msys2/${PACKAGE_NAME}.zip.sha256" "${API_BASE}/${PACKAGE_NAME}.zip.sha256"
|
||||
upload_file "dist-windows-msys2/${PACKAGE_NAME}.zip.parts.sha256" "${API_BASE}/${PACKAGE_NAME}.zip.parts.sha256"
|
||||
echo "Package uploaded to: ${API_BASE}/"
|
||||
echo "Download all ${PACKAGE_NAME}.zip.part-* files, then reconstruct with: cat ${PACKAGE_NAME}.zip.part-* > ${PACKAGE_NAME}.zip"
|
||||
@@ -1,211 +1,108 @@
|
||||
name: Build Windows Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build-windows-release:
|
||||
name: Windows x64 Release (MinGW + Qt + OpenCV)
|
||||
runs-on: ubuntu-latest
|
||||
container: fedora:latest
|
||||
|
||||
env:
|
||||
BUILD_TYPE: Release
|
||||
APP_NAME: QtOpenCVImageTool
|
||||
PACKAGE_BASENAME: QtOpenCVImageTool-windows-x64
|
||||
build-windows:
|
||||
# Gitea Actions 使用自建 act_runner,不提供 GitHub 托管的 windows-latest。
|
||||
# 这里匹配常见的 Windows Runner 标签;Runner 需注册为 windows 或 windows-latest 才会接单。
|
||||
runs-on:
|
||||
- windows
|
||||
defaults:
|
||||
run:
|
||||
shell: msys2 {0}
|
||||
|
||||
steps:
|
||||
- name: Configure Fedora 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 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: Setup MSYS2 build environment
|
||||
uses: msys2/setup-msys2@v2
|
||||
with:
|
||||
msystem: UCRT64
|
||||
update: true
|
||||
install: >-
|
||||
git
|
||||
zip
|
||||
p7zip
|
||||
mingw-w64-ucrt-x86_64-toolchain
|
||||
mingw-w64-ucrt-x86_64-cmake
|
||||
mingw-w64-ucrt-x86_64-ninja
|
||||
mingw-w64-ucrt-x86_64-qt6-base
|
||||
mingw-w64-ucrt-x86_64-opencv
|
||||
|
||||
- name: Configure
|
||||
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
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_PREFIX_PATH=/ucrt64
|
||||
|
||||
- name: Build
|
||||
run: cmake --build build-windows --config "$BUILD_TYPE" --parallel
|
||||
run: |
|
||||
cmake --build build-windows --parallel "$(nproc)"
|
||||
|
||||
- name: Package
|
||||
run: |
|
||||
set -euo pipefail
|
||||
root="/usr/x86_64-w64-mingw32/sys-root/mingw"
|
||||
dist="dist-windows/$APP_NAME"
|
||||
rm -rf dist-windows artifacts
|
||||
mkdir -p "$dist/platforms" "$dist/imageformats" artifacts
|
||||
APP_NAME="chengnan"
|
||||
PACKAGE_NAME="chengnan-windows-x86_64"
|
||||
PACKAGE_DIR="dist-windows/${PACKAGE_NAME}"
|
||||
EXE="build-windows/${APP_NAME}.exe"
|
||||
|
||||
cp "build-windows/$APP_NAME.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*.dll" -exec cp -t "$dist/" {} +
|
||||
install -m 0644 readme.md "$dist/readme.md"
|
||||
test -f "$EXE"
|
||||
rm -rf dist-windows
|
||||
mkdir -p "$PACKAGE_DIR"
|
||||
cp "$EXE" "$PACKAGE_DIR/"
|
||||
|
||||
cat > "$dist/README.txt" <<EOF
|
||||
$APP_NAME Windows x64 package
|
||||
|
||||
Usage:
|
||||
1. Extract the whole directory.
|
||||
2. Double-click $APP_NAME.exe to run.
|
||||
|
||||
Do not copy the exe alone. Keep DLL files and Qt plugin directories together.
|
||||
EOF
|
||||
|
||||
short_sha="${GITHUB_SHA::10}"
|
||||
if [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then
|
||||
version="$GITHUB_REF_NAME"
|
||||
# 部署 Qt 运行时和插件。
|
||||
if command -v windeployqt >/dev/null 2>&1; then
|
||||
windeployqt --release --no-translations "$PACKAGE_DIR/${APP_NAME}.exe"
|
||||
elif command -v windeployqt6 >/dev/null 2>&1; then
|
||||
windeployqt6 --release --no-translations "$PACKAGE_DIR/${APP_NAME}.exe"
|
||||
else
|
||||
version="build-$short_sha"
|
||||
echo "windeployqt not found" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
package="$PACKAGE_BASENAME-$version.zip"
|
||||
(cd dist-windows && zip -r "../artifacts/$package" "$APP_NAME")
|
||||
sha256sum "artifacts/$package" > "artifacts/$package.sha256"
|
||||
printf 'VERSION=%s\n' "$version" >> "$GITHUB_ENV"
|
||||
printf 'PACKAGE=%s\n' "$package" >> "$GITHUB_ENV"
|
||||
# 收集 MinGW/MSYS2/OpenCV 运行时 DLL。ldd 会列出 exe/dll 依赖;循环几轮收集二级依赖。
|
||||
for round in 1 2 3; do
|
||||
while IFS= read -r binary; do
|
||||
while IFS= read -r dll; do
|
||||
[ -f "$dll" ] || continue
|
||||
cp -n "$dll" "$PACKAGE_DIR/" || true
|
||||
done < <(ldd "$binary" \
|
||||
| awk '/=> \/ucrt64\/bin\// {print $3} /^\/ucrt64\/bin\// {print $1}' \
|
||||
| sort -u)
|
||||
done < <(find "$PACKAGE_DIR" -maxdepth 2 -type f \( -name '*.exe' -o -name '*.dll' \) | sort)
|
||||
done
|
||||
|
||||
cat > "$PACKAGE_DIR/README.txt" <<'EOF'
|
||||
chengnan Windows x86_64 发布包
|
||||
|
||||
运行方式:
|
||||
1. 解压整个目录。
|
||||
2. 双击 chengnan.exe 运行。
|
||||
|
||||
说明:
|
||||
- 本目录已包含 Qt、OpenCV 和 MinGW 运行时 DLL。
|
||||
- 请不要只复制 chengnan.exe,需保留同目录 DLL 和 Qt plugins 子目录。
|
||||
EOF
|
||||
|
||||
(cd dist-windows && 7z a -tzip "${PACKAGE_NAME}.zip" "${PACKAGE_NAME}" >/dev/null)
|
||||
(cd dist-windows && sha256sum "${PACKAGE_NAME}.zip" > "${PACKAGE_NAME}.zip.sha256")
|
||||
|
||||
- name: Verify package
|
||||
run: |
|
||||
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
|
||||
sha256sum -c "artifacts/$PACKAGE.sha256"
|
||||
test -s dist-windows/chengnan-windows-x86_64.zip
|
||||
sha256sum -c dist-windows/chengnan-windows-x86_64.zip.sha256
|
||||
7z l dist-windows/chengnan-windows-x86_64.zip | grep 'chengnan.exe'
|
||||
|
||||
- name: Upload package to Gitea 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
|
||||
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="$APP_NAME ${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." \
|
||||
--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
|
||||
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
|
||||
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}" \
|
||||
--output upload-response.json \
|
||||
"$api_base/releases/$release_id/assets?name=$encoded_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"
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: chengnan-windows-x86_64
|
||||
path: |
|
||||
dist-windows/chengnan-windows-x86_64.zip
|
||||
dist-windows/chengnan-windows-x86_64.zip.sha256
|
||||
if-no-files-found: error
|
||||
|
||||
+49
-11
@@ -1,14 +1,52 @@
|
||||
build/
|
||||
build-windows/
|
||||
build-wsl-windows/
|
||||
cmake-build-*/
|
||||
.qt/
|
||||
.qtc/
|
||||
CMakeUserPresets.json
|
||||
*.user
|
||||
*.suo
|
||||
*.vcxproj*
|
||||
*.sln
|
||||
# 构建输出与发布产物
|
||||
/build*/
|
||||
/dist*/
|
||||
/out*/
|
||||
/release*/
|
||||
/debug*/
|
||||
|
||||
# 编译工具、SDK、第三方依赖缓存
|
||||
# 本仓库只保存源码;CMake/Ninja/Qt/OpenCV/MSYS2/vcpkg 等均由工作流临时安装。
|
||||
/tools/
|
||||
/third_party/
|
||||
/downloads/
|
||||
/.cache/
|
||||
/vcpkg_installed/
|
||||
|
||||
# CMake / Ninja / 编译数据库
|
||||
CMakeCache.txt
|
||||
CMakeFiles/
|
||||
cmake_install.cmake
|
||||
install_manifest.txt
|
||||
.ninja_*
|
||||
build.ninja
|
||||
compile_commands.json
|
||||
|
||||
# Windows / Qt / C++ 本地产物
|
||||
*.exe
|
||||
*.dll
|
||||
*.lib
|
||||
*.pdb
|
||||
*.ilk
|
||||
*.obj
|
||||
*.exp
|
||||
*.manifest
|
||||
*.qrc.depends
|
||||
moc_*.cpp
|
||||
qrc_*.cpp
|
||||
ui_*.h
|
||||
*_autogen/
|
||||
|
||||
# 日志和临时文件
|
||||
*.log
|
||||
*.tmp
|
||||
*.bak
|
||||
*.swp
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.user
|
||||
*.pro.user
|
||||
|
||||
+60
-22
@@ -1,30 +1,68 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
|
||||
project(QtOpenCVImageTool LANGUAGES CXX)
|
||||
project(chengnan VERSION 0.1.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)
|
||||
|
||||
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)
|
||||
find_package(OpenCV REQUIRED)
|
||||
|
||||
add_executable(QtOpenCVImageTool WIN32
|
||||
main.cpp
|
||||
MainWindow.h
|
||||
MainWindow.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(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 Concurrent)
|
||||
if (NOT Qt6_FOUND)
|
||||
find_package(Qt5 REQUIRED COMPONENTS Widgets Concurrent)
|
||||
endif()
|
||||
|
||||
find_package(OpenCV REQUIRED COMPONENTS core imgproc imgcodecs)
|
||||
|
||||
# Fedora MinGW OpenCV 4.13.0 may report an invalid include directory
|
||||
# (//include/opencv4) from its OpenCVConfig.cmake. The headers are in the
|
||||
# MinGW sysroot, so add a narrow cross-build fallback when CMake did not get a
|
||||
# usable OpenCV include path from the package config.
|
||||
if (MINGW AND (NOT OpenCV_INCLUDE_DIRS OR NOT EXISTS "${OpenCV_INCLUDE_DIRS}"))
|
||||
set(_fedora_mingw_opencv_include "/usr/x86_64-w64-mingw32/sys-root/mingw/include/opencv4")
|
||||
if (EXISTS "${_fedora_mingw_opencv_include}")
|
||||
set(OpenCV_INCLUDE_DIRS "${_fedora_mingw_opencv_include}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
set(PROJECT_SOURCES
|
||||
app/src/main.cpp
|
||||
app/src/MainWindow.cpp
|
||||
app/src/ImageView.cpp
|
||||
app/src/ImageConverter.cpp
|
||||
app/src/ImageProcessor.cpp
|
||||
app/src/ImageWorker.cpp
|
||||
|
||||
app/include/MainWindow.h
|
||||
app/include/ImageView.h
|
||||
app/include/ImageConverter.h
|
||||
app/include/ImageProcessor.h
|
||||
app/include/ImageWorker.h
|
||||
)
|
||||
|
||||
if (Qt6_FOUND)
|
||||
qt_add_executable(chengnan ${PROJECT_SOURCES})
|
||||
target_link_libraries(chengnan PRIVATE Qt6::Widgets Qt6::Concurrent ${OpenCV_LIBS})
|
||||
else()
|
||||
add_executable(chengnan ${PROJECT_SOURCES})
|
||||
target_link_libraries(chengnan PRIVATE Qt5::Widgets Qt5::Concurrent ${OpenCV_LIBS})
|
||||
endif()
|
||||
|
||||
target_include_directories(chengnan PRIVATE
|
||||
${OpenCV_INCLUDE_DIRS}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/app/include
|
||||
)
|
||||
|
||||
target_compile_definitions(chengnan PRIVATE
|
||||
QT_NO_KEYWORDS
|
||||
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)
|
||||
|
||||
-433
@@ -1,433 +0,0 @@
|
||||
#include "MainWindow.h"
|
||||
|
||||
#include <QCheckBox>
|
||||
#include <QFileDialog>
|
||||
#include <QFileInfo>
|
||||
#include <QGroupBox>
|
||||
#include <QHBoxLayout>
|
||||
#include <QImage>
|
||||
#include <QLabel>
|
||||
#include <QMessageBox>
|
||||
#include <QPushButton>
|
||||
#include <QPixmap>
|
||||
#include <QScrollArea>
|
||||
#include <QSlider>
|
||||
#include <QStatusBar>
|
||||
#include <QThread>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace
|
||||
{
|
||||
QImage matToQImage(const cv::Mat &mat)
|
||||
{
|
||||
if (mat.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
cv::Mat rgb;
|
||||
if (mat.channels() == 1) {
|
||||
cv::cvtColor(mat, rgb, cv::COLOR_GRAY2RGB);
|
||||
} else if (mat.channels() == 3) {
|
||||
cv::cvtColor(mat, rgb, cv::COLOR_BGR2RGB);
|
||||
} else if (mat.channels() == 4) {
|
||||
cv::cvtColor(mat, rgb, cv::COLOR_BGRA2RGBA);
|
||||
} else {
|
||||
return {};
|
||||
}
|
||||
|
||||
const QImage::Format format = rgb.channels() == 4 ? QImage::Format_RGBA8888 : QImage::Format_RGB888;
|
||||
return QImage(rgb.data, rgb.cols, rgb.rows, static_cast<int>(rgb.step), format).copy();
|
||||
}
|
||||
|
||||
cv::Mat rotateWithBounds(const cv::Mat &image, double angle)
|
||||
{
|
||||
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 {};
|
||||
}
|
||||
|
||||
cv::Mat gray;
|
||||
cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
|
||||
cv::GaussianBlur(gray, gray, cv::Size(5, 5), 0);
|
||||
|
||||
cv::Mat binary;
|
||||
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
|
||||
if (cv::countNonZero(binary) > binary.rows * binary.cols / 2) {
|
||||
cv::bitwise_not(binary, binary);
|
||||
}
|
||||
|
||||
const cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 5));
|
||||
cv::morphologyEx(binary, binary, cv::MORPH_OPEN, kernel);
|
||||
cv::morphologyEx(binary, binary, cv::MORPH_CLOSE, kernel);
|
||||
|
||||
std::vector<std::vector<cv::Point>> contours;
|
||||
cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
|
||||
|
||||
cv::Mat extracted = cv::Mat::zeros(image.size(), image.type());
|
||||
image.copyTo(extracted, binary);
|
||||
|
||||
for (const auto &contour : contours) {
|
||||
const double area = cv::contourArea(contour);
|
||||
if (area < 300.0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
++targetCount;
|
||||
cv::rectangle(extracted, cv::boundingRect(contour), cv::Scalar(0, 255, 0), 2);
|
||||
}
|
||||
|
||||
return extracted;
|
||||
}
|
||||
|
||||
QString classifyImage(const cv::Mat &image, int targetCount)
|
||||
{
|
||||
if (image.empty()) {
|
||||
return QStringLiteral("未载入图片");
|
||||
}
|
||||
|
||||
cv::Scalar mean = cv::mean(image);
|
||||
const double brightness = (mean[0] + mean[1] + mean[2]) / 3.0;
|
||||
const QString light = brightness >= 170.0 ? QStringLiteral("偏亮")
|
||||
: brightness <= 85.0 ? QStringLiteral("偏暗")
|
||||
: QStringLiteral("亮度适中");
|
||||
|
||||
QString color = QStringLiteral("颜色均衡");
|
||||
if (mean[2] > mean[1] + 18.0 && mean[2] > mean[0] + 18.0) {
|
||||
color = QStringLiteral("红色占优");
|
||||
} else if (mean[1] > mean[2] + 18.0 && mean[1] > mean[0] + 18.0) {
|
||||
color = QStringLiteral("绿色占优");
|
||||
} else if (mean[0] > mean[2] + 18.0 && mean[0] > mean[1] + 18.0) {
|
||||
color = QStringLiteral("蓝色占优");
|
||||
}
|
||||
|
||||
return QStringLiteral("分类结果:%1,%2;目标数量:%3").arg(light, color).arg(targetCount);
|
||||
}
|
||||
|
||||
class ImageProcessorWorker : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public slots:
|
||||
void process(const cv::Mat &source, const ProcessParams ¶ms)
|
||||
{
|
||||
if (source.empty()) {
|
||||
emit processed(cv::Mat(), QStringLiteral("未载入图片"));
|
||||
return;
|
||||
}
|
||||
|
||||
cv::Mat output = source.clone();
|
||||
|
||||
if (std::abs(params.scale - 1.0) > 0.001) {
|
||||
cv::resize(output, output, cv::Size(), params.scale, params.scale, cv::INTER_LINEAR);
|
||||
}
|
||||
|
||||
output = translateImage(output, params.translateX, params.translateY);
|
||||
output = rotateWithBounds(output, params.angle);
|
||||
|
||||
int targetCount = 0;
|
||||
if (params.extractTarget) {
|
||||
output = extractTargets(output, targetCount);
|
||||
} else {
|
||||
cv::Mat gray;
|
||||
cv::cvtColor(output, gray, cv::COLOR_BGR2GRAY);
|
||||
cv::Mat binary;
|
||||
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
|
||||
std::vector<std::vector<cv::Point>> contours;
|
||||
cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
|
||||
targetCount = static_cast<int>(std::count_if(contours.begin(), contours.end(), [](const auto &contour) {
|
||||
return cv::contourArea(contour) >= 300.0;
|
||||
}));
|
||||
}
|
||||
|
||||
const QString classText = params.classifyImage ? classifyImage(output, targetCount) : QStringLiteral("处理完成");
|
||||
emit processed(output, classText);
|
||||
}
|
||||
|
||||
signals:
|
||||
void processed(const cv::Mat &image, const QString &classText);
|
||||
};
|
||||
}
|
||||
|
||||
MainWindow::MainWindow(QWidget *parent)
|
||||
: QMainWindow(parent)
|
||||
{
|
||||
qRegisterMetaType<cv::Mat>("cv::Mat");
|
||||
qRegisterMetaType<ProcessParams>("ProcessParams");
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
MainWindow::~MainWindow()
|
||||
{
|
||||
if (workerThread) {
|
||||
workerThread->quit();
|
||||
workerThread->wait();
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::buildUi()
|
||||
{
|
||||
setWindowTitle(QStringLiteral("Qt + OpenCV 图像显示与处理"));
|
||||
|
||||
auto *central = new QWidget(this);
|
||||
auto *rootLayout = new QVBoxLayout(central);
|
||||
|
||||
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);
|
||||
|
||||
auto *controlBox = new QGroupBox(QStringLiteral("图像处理"));
|
||||
auto *controlLayout = new QHBoxLayout(controlBox);
|
||||
|
||||
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("图像分类"));
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
addSlider(QStringLiteral("缩放"), scaleSlider);
|
||||
addSlider(QStringLiteral("旋转"), rotateSlider);
|
||||
addSlider(QStringLiteral("水平平移"), translateXSlider);
|
||||
addSlider(QStringLiteral("垂直平移"), translateYSlider);
|
||||
controlLayout->addWidget(extractCheckBox);
|
||||
controlLayout->addWidget(classifyCheckBox);
|
||||
|
||||
auto *imageLayout = new QHBoxLayout;
|
||||
originalLabel = new QLabel(QStringLiteral("原图"));
|
||||
resultLabel = new QLabel(QStringLiteral("处理后图像"));
|
||||
originalLabel->setAlignment(Qt::AlignCenter);
|
||||
resultLabel->setAlignment(Qt::AlignCenter);
|
||||
originalLabel->setMinimumSize(480, 420);
|
||||
resultLabel->setMinimumSize(480, 420);
|
||||
originalLabel->setStyleSheet("QLabel { background:#202124; color:white; border:1px solid #555; }");
|
||||
resultLabel->setStyleSheet("QLabel { background:#202124; color:white; border:1px solid #555; }");
|
||||
|
||||
auto *originalScroll = new QScrollArea;
|
||||
auto *resultScroll = new QScrollArea;
|
||||
originalScroll->setWidget(originalLabel);
|
||||
resultScroll->setWidget(resultLabel);
|
||||
originalScroll->setWidgetResizable(true);
|
||||
resultScroll->setWidgetResizable(true);
|
||||
|
||||
imageLayout->addWidget(originalScroll, 1);
|
||||
imageLayout->addWidget(resultScroll, 1);
|
||||
|
||||
rootLayout->addLayout(buttonLayout);
|
||||
rootLayout->addWidget(controlBox);
|
||||
rootLayout->addLayout(imageLayout, 1);
|
||||
setCentralWidget(central);
|
||||
|
||||
statusLabel = new QLabel(QStringLiteral("请打开一张图片"));
|
||||
statusBar()->addWidget(statusLabel, 1);
|
||||
|
||||
connect(openButton, &QPushButton::clicked, this, &MainWindow::openImage);
|
||||
connect(saveButton, &QPushButton::clicked, this, &MainWindow::saveImage);
|
||||
connect(saveAsButton, &QPushButton::clicked, this, &MainWindow::saveImageAs);
|
||||
connect(resetButton, &QPushButton::clicked, this, &MainWindow::resetParams);
|
||||
|
||||
connect(scaleSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
|
||||
connect(rotateSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
|
||||
connect(translateXSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
|
||||
connect(translateYSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
|
||||
connect(extractCheckBox, &QCheckBox::toggled, this, &MainWindow::scheduleProcessing);
|
||||
connect(classifyCheckBox, &QCheckBox::toggled, this, &MainWindow::scheduleProcessing);
|
||||
}
|
||||
|
||||
void MainWindow::openImage()
|
||||
{
|
||||
const QString fileName = QFileDialog::getOpenFileName(
|
||||
this,
|
||||
QStringLiteral("打开图片"),
|
||||
QString(),
|
||||
QStringLiteral("Images (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)"));
|
||||
|
||||
if (fileName.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
originalImage = cv::imread(fileName.toLocal8Bit().constData(), cv::IMREAD_COLOR);
|
||||
if (originalImage.empty()) {
|
||||
QMessageBox::warning(this, QStringLiteral("打开失败"), QStringLiteral("无法读取该图片文件。"));
|
||||
return;
|
||||
}
|
||||
|
||||
savePath.clear();
|
||||
updateOriginalView();
|
||||
scheduleProcessing();
|
||||
statusLabel->setText(QStringLiteral("已打开:%1").arg(QFileInfo(fileName).fileName()));
|
||||
}
|
||||
|
||||
void MainWindow::saveImage()
|
||||
{
|
||||
if (savePath.isEmpty()) {
|
||||
saveImageAs();
|
||||
return;
|
||||
}
|
||||
|
||||
if (writeResultToFile(savePath)) {
|
||||
statusLabel->setText(QStringLiteral("已保存:%1").arg(QFileInfo(savePath).fileName()));
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::saveImageAs()
|
||||
{
|
||||
if (resultImage.empty()) {
|
||||
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("请先打开并处理图片。"));
|
||||
return;
|
||||
}
|
||||
|
||||
const QString fileName = QFileDialog::getSaveFileName(
|
||||
this,
|
||||
QStringLiteral("另存图片"),
|
||||
QStringLiteral("processed.png"),
|
||||
QStringLiteral("PNG (*.png);;JPEG (*.jpg *.jpeg);;BMP (*.bmp);;TIFF (*.tif *.tiff)"));
|
||||
|
||||
if (fileName.isEmpty()) {
|
||||
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()) {
|
||||
return;
|
||||
}
|
||||
|
||||
emit processRequested(originalImage.clone(), currentParams());
|
||||
}
|
||||
|
||||
void MainWindow::onProcessed(const cv::Mat &image, const QString &classText)
|
||||
{
|
||||
resultImage = image.clone();
|
||||
updateResultView();
|
||||
statusLabel->setText(classText);
|
||||
}
|
||||
|
||||
void MainWindow::updateOriginalView()
|
||||
{
|
||||
setImageOnLabel(originalLabel, originalImage);
|
||||
}
|
||||
|
||||
void MainWindow::updateResultView()
|
||||
{
|
||||
setImageOnLabel(resultLabel, resultImage);
|
||||
}
|
||||
|
||||
void MainWindow::setImageOnLabel(QLabel *label, const cv::Mat &mat)
|
||||
{
|
||||
const QImage image = matToQImage(mat);
|
||||
if (image.isNull()) {
|
||||
label->setText(QStringLiteral("无图像"));
|
||||
return;
|
||||
}
|
||||
|
||||
label->setPixmap(QPixmap::fromImage(image).scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
|
||||
}
|
||||
|
||||
ProcessParams MainWindow::currentParams() const
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
bool MainWindow::writeResultToFile(const QString &fileName)
|
||||
{
|
||||
if (resultImage.empty()) {
|
||||
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("没有可保存的处理结果。"));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!cv::imwrite(fileName.toLocal8Bit().constData(), resultImage)) {
|
||||
QMessageBox::warning(this, QStringLiteral("保存失败"), QStringLiteral("无法写入该图片文件。"));
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
#include "MainWindow.moc"
|
||||
@@ -1,76 +0,0 @@
|
||||
#ifndef MAINWINDOW_H
|
||||
#define MAINWINDOW_H
|
||||
|
||||
#include <QMainWindow>
|
||||
#include <QMetaType>
|
||||
|
||||
#include <opencv2/opencv.hpp>
|
||||
|
||||
class QLabel;
|
||||
class QPushButton;
|
||||
class QSlider;
|
||||
class QCheckBox;
|
||||
class QThread;
|
||||
|
||||
struct ProcessParams
|
||||
{
|
||||
double scale = 1.0;
|
||||
int translateX = 0;
|
||||
int translateY = 0;
|
||||
double angle = 0.0;
|
||||
bool extractTarget = false;
|
||||
bool classifyImage = false;
|
||||
};
|
||||
|
||||
Q_DECLARE_METATYPE(cv::Mat)
|
||||
Q_DECLARE_METATYPE(ProcessParams)
|
||||
|
||||
class MainWindow : public QMainWindow
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit MainWindow(QWidget *parent = nullptr);
|
||||
~MainWindow() override;
|
||||
|
||||
signals:
|
||||
void processRequested(const cv::Mat &image, const ProcessParams ¶ms);
|
||||
|
||||
private slots:
|
||||
void openImage();
|
||||
void saveImage();
|
||||
void saveImageAs();
|
||||
void resetParams();
|
||||
void scheduleProcessing();
|
||||
void onProcessed(const cv::Mat &image, const QString &classText);
|
||||
|
||||
private:
|
||||
void buildUi();
|
||||
void updateOriginalView();
|
||||
void updateResultView();
|
||||
void setImageOnLabel(QLabel *label, const cv::Mat &mat);
|
||||
ProcessParams currentParams() const;
|
||||
bool writeResultToFile(const QString &fileName);
|
||||
|
||||
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;
|
||||
|
||||
cv::Mat originalImage;
|
||||
cv::Mat resultImage;
|
||||
QString savePath;
|
||||
|
||||
QThread *workerThread = nullptr;
|
||||
};
|
||||
|
||||
#endif
|
||||
Binary file not shown.
@@ -0,0 +1,135 @@
|
||||
# chengnan
|
||||
|
||||
chengnan 是一个面向 Windows 的图片查看器 / 简单图像处理应用,使用 **Qt Widgets + OpenCV + CMake + C++17** 开发。
|
||||
|
||||
## 项目定位
|
||||
|
||||
- 目标平台:Windows x64
|
||||
- 应用类型:桌面图片查看器
|
||||
- 构建方式:只在 Gitea Actions 工作流中构建和打包
|
||||
- 仓库内容:只保留源码、CMake 配置、文档和工作流
|
||||
- 仓库不包含:CMake/Ninja/Qt/OpenCV/MSYS2/vcpkg 等编译工具、SDK、第三方二进制依赖、本地构建产物
|
||||
|
||||
## 功能
|
||||
|
||||
当前已实现:
|
||||
|
||||
- 打开图片
|
||||
- 保存图片、另存图片
|
||||
- 使用 Qt QWidget 体系显示图片,不使用 `cv::imshow`
|
||||
- 左右对比显示原图和处理后图片
|
||||
- 图片视图支持:
|
||||
- 鼠标滚轮缩放
|
||||
- 双击适配窗口
|
||||
- 拖拽平移视图
|
||||
- 基础图像处理:
|
||||
- 放大 / 缩小
|
||||
- 平移
|
||||
- 指定角度旋转
|
||||
- 阈值分割 + 轮廓目标提取
|
||||
- 基于 HSV 均值的简单规则分类
|
||||
- 使用 `QThread` + 信号槽执行 OpenCV 处理任务,避免阻塞 UI
|
||||
|
||||
## 技术栈
|
||||
|
||||
- C++17
|
||||
- Qt Widgets / Qt Concurrent
|
||||
- OpenCV
|
||||
- CMake
|
||||
- Gitea Actions
|
||||
|
||||
## 目录结构
|
||||
|
||||
```text
|
||||
chengnan/
|
||||
├── .gitea/workflows/
|
||||
│ ├── build-windows-cross-linux.yml # Linux Runner 交叉编译 Windows 发布包
|
||||
│ └── build-windows-release.yml # Windows Runner 原生构建备用工作流
|
||||
├── app/
|
||||
│ ├── include/ # 头文件
|
||||
│ └── src/ # 源文件
|
||||
├── CMakeLists.txt
|
||||
├── .gitignore
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## 构建与发布
|
||||
|
||||
本项目不在仓库中保存编译工具或第三方二进制依赖。所有构建工作都在 Gitea Actions 工作流中完成。
|
||||
|
||||
当前优先使用 `.gitea/workflows/build-windows-cross-linux.yml`:在自建 `9950x` Linux Runner 的 Fedora 41 容器中,通过 MinGW-w64 交叉编译生成 Windows x86_64 发布包。`.gitea/workflows/build-windows-release.yml` 保留为 Windows Runner 原生构建备用工作流。
|
||||
|
||||
交叉编译工作流会临时完成以下步骤:
|
||||
|
||||
1. 拉取源码
|
||||
2. 安装 Fedora / MinGW-w64 构建环境和依赖
|
||||
3. 配置 CMake
|
||||
4. 编译 Release 版本
|
||||
5. 收集 Qt / OpenCV / MinGW 运行时依赖
|
||||
6. 打包 Windows 发布包
|
||||
7. 生成 SHA256 校验文件
|
||||
8. 上传发布包到 Gitea Packages
|
||||
|
||||
## 编译工具链版本
|
||||
|
||||
交叉编译工作流固定使用以下环境和包版本:
|
||||
|
||||
| 组件 | 版本 |
|
||||
| --- | --- |
|
||||
| Runner 标签 | `9950x` |
|
||||
| 容器镜像 | `fedora:41` |
|
||||
| C++ 语言标准 | `C++17` |
|
||||
| MinGW-w64 GCC C++ | `mingw64-gcc-c++ 14.2.1-3.fc41` |
|
||||
| CMake | `cmake 3.28.3-7.fc41` |
|
||||
| Ninja | `ninja-build 1.12.1-3.fc41` |
|
||||
| Qt 6 Base | `mingw64-qt6-qtbase 6.7.2-3.fc41` |
|
||||
| OpenCV | `mingw64-opencv 4.10.0-1.fc41` |
|
||||
|
||||
版本来源为 Fedora 41 `Everything/x86_64` 仓库元数据;构建时由工作流临时安装,不提交到源码仓库。
|
||||
|
||||
触发方式:
|
||||
|
||||
- push 到 `main`
|
||||
- 创建 `v*` 标签
|
||||
- Pull Request 到 `main`
|
||||
- 手动触发 `workflow_dispatch`
|
||||
|
||||
构建产物:
|
||||
|
||||
```text
|
||||
chengnan-windows-x86_64-cross.zip
|
||||
chengnan-windows-x86_64-cross.zip.sha256
|
||||
```
|
||||
|
||||
发布包解压后,双击 `chengnan.exe` 运行。请保留同目录 DLL 和 Qt 插件目录,不要只复制单个 exe。
|
||||
|
||||
## 本地开发说明
|
||||
|
||||
仓库不提供本地依赖安装脚本,也不保存编译工具。若需要本地开发,请自行在 Windows 上安装:
|
||||
|
||||
- CMake
|
||||
- Ninja
|
||||
- Qt 6
|
||||
- OpenCV
|
||||
- C++ 编译器(MSVC 或 MinGW)
|
||||
|
||||
然后按常规 CMake 项目方式配置和构建。正式发布以 Gitea Actions 产物为准。
|
||||
|
||||
## 依赖管理原则
|
||||
|
||||
- 不提交编译器、CMake、Ninja、Qt、OpenCV、MSYS2、vcpkg 等工具或 SDK
|
||||
- 不提交 `build-*`、`dist-*`、`.exe`、`.dll` 等构建产物
|
||||
- 第三方依赖只在工作流运行期间临时安装
|
||||
- 发布包只作为工作流产物或 Gitea Packages 文件产出,不进入源码仓库
|
||||
|
||||
## 验收标准
|
||||
|
||||
- 可以打开常见图片格式,例如 PNG、JPG、BMP
|
||||
- 可以保存当前处理后的图片
|
||||
- 可以另存为指定路径
|
||||
- 可以在同一界面中对比显示处理前和处理后图片
|
||||
- 支持缩放、平移、旋转操作
|
||||
- 至少实现目标提取或分类功能之一
|
||||
- 图片显示使用 QWidget 体系,不使用 OpenCV 窗口显示函数
|
||||
- 图像处理任务不会明显阻塞 UI
|
||||
- Windows 发布包可直接解压运行
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <QImage>
|
||||
#include <opencv2/core.hpp>
|
||||
|
||||
class ImageConverter final
|
||||
{
|
||||
public:
|
||||
static QImage matToQImage(const cv::Mat &mat);
|
||||
static cv::Mat qImageToMat(const QImage &image);
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <QString>
|
||||
#include <QMetaType>
|
||||
#include <opencv2/core.hpp>
|
||||
|
||||
struct ProcessResult
|
||||
{
|
||||
cv::Mat image;
|
||||
QString description;
|
||||
};
|
||||
|
||||
class ImageProcessor final
|
||||
{
|
||||
public:
|
||||
static ProcessResult rotate(const cv::Mat &source, double angleDegrees);
|
||||
static ProcessResult scale(const cv::Mat &source, double factor);
|
||||
static ProcessResult translate(const cv::Mat &source, int dx, int dy);
|
||||
static ProcessResult extractTargets(const cv::Mat &source);
|
||||
static ProcessResult classifySimple(const cv::Mat &source);
|
||||
};
|
||||
|
||||
Q_DECLARE_METATYPE(ProcessResult)
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <QGraphicsView>
|
||||
#include <QImage>
|
||||
#include <QPixmap>
|
||||
|
||||
class QGraphicsPixmapItem;
|
||||
class QGraphicsScene;
|
||||
class QWheelEvent;
|
||||
class QMouseEvent;
|
||||
|
||||
class ImageView final : public QGraphicsView
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit ImageView(QWidget *parent = nullptr);
|
||||
|
||||
void setImage(const QImage &image);
|
||||
void clearImage();
|
||||
void fitImageToView();
|
||||
bool hasImage() const;
|
||||
|
||||
protected:
|
||||
void wheelEvent(QWheelEvent *event) override;
|
||||
void mouseDoubleClickEvent(QMouseEvent *event) override;
|
||||
|
||||
private:
|
||||
void resetSceneRect();
|
||||
|
||||
QGraphicsScene *scene_ = nullptr;
|
||||
QGraphicsPixmapItem *pixmapItem_ = nullptr;
|
||||
QPixmap pixmap_;
|
||||
double zoomFactor_ = 1.0;
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include "ImageProcessor.h"
|
||||
|
||||
#include <QObject>
|
||||
#include <QMetaType>
|
||||
#include <opencv2/core.hpp>
|
||||
|
||||
Q_DECLARE_METATYPE(cv::Mat)
|
||||
|
||||
class ImageWorker final : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
enum class Operation {
|
||||
Rotate,
|
||||
Scale,
|
||||
Translate,
|
||||
ExtractTargets,
|
||||
ClassifySimple
|
||||
};
|
||||
Q_ENUM(Operation)
|
||||
|
||||
public Q_SLOTS:
|
||||
void process(cv::Mat image, ImageWorker::Operation operation, double value, int dx, int dy);
|
||||
|
||||
Q_SIGNALS:
|
||||
void finished(ProcessResult result);
|
||||
void failed(QString message);
|
||||
};
|
||||
|
||||
Q_DECLARE_METATYPE(ImageWorker::Operation)
|
||||
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include "ImageWorker.h"
|
||||
|
||||
#include <QMainWindow>
|
||||
#include <QThread>
|
||||
#include <opencv2/core.hpp>
|
||||
|
||||
class QAction;
|
||||
class QLabel;
|
||||
class QSpinBox;
|
||||
class QDoubleSpinBox;
|
||||
class QPushButton;
|
||||
class ImageView;
|
||||
|
||||
class MainWindow final : public QMainWindow
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit MainWindow(QWidget *parent = nullptr);
|
||||
~MainWindow() override;
|
||||
|
||||
Q_SIGNALS:
|
||||
void processRequested(cv::Mat image, ImageWorker::Operation operation, double value, int dx, int dy);
|
||||
|
||||
private Q_SLOTS:
|
||||
void openImage();
|
||||
void saveImage();
|
||||
void saveImageAs();
|
||||
void resetToOriginal();
|
||||
void onProcessFinished(ProcessResult result);
|
||||
void onProcessFailed(const QString &message);
|
||||
void rotateLeft();
|
||||
void rotateRight();
|
||||
void scaleUp();
|
||||
void scaleDown();
|
||||
void translateUp();
|
||||
void translateDown();
|
||||
void translateLeft();
|
||||
void translateRight();
|
||||
void extractTargets();
|
||||
void classifyImage();
|
||||
|
||||
private:
|
||||
void buildUi();
|
||||
void setupWorkerThread();
|
||||
void updateViews();
|
||||
void setBusy(bool busy);
|
||||
bool ensureHasImage() const;
|
||||
void requestProcess(ImageWorker::Operation operation, double value = 0.0, int dx = 0, int dy = 0);
|
||||
bool writeCurrentImageTo(const QString &path);
|
||||
|
||||
ImageView *originalView_ = nullptr;
|
||||
ImageView *processedView_ = nullptr;
|
||||
QLabel *infoLabel_ = nullptr;
|
||||
QLabel *statusLabel_ = nullptr;
|
||||
QDoubleSpinBox *scaleSpin_ = nullptr;
|
||||
QDoubleSpinBox *angleSpin_ = nullptr;
|
||||
QSpinBox *translateSpin_ = nullptr;
|
||||
|
||||
QAction *saveAction_ = nullptr;
|
||||
QAction *saveAsAction_ = nullptr;
|
||||
|
||||
QThread workerThread_;
|
||||
ImageWorker *worker_ = nullptr;
|
||||
|
||||
cv::Mat originalImage_;
|
||||
cv::Mat processedImage_;
|
||||
QString currentPath_;
|
||||
bool busy_ = false;
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
#include "ImageConverter.h"
|
||||
|
||||
#include <opencv2/imgproc.hpp>
|
||||
|
||||
QImage ImageConverter::matToQImage(const cv::Mat &mat)
|
||||
{
|
||||
if (mat.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
switch (mat.type()) {
|
||||
case CV_8UC1: {
|
||||
QImage image(mat.data, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_Grayscale8);
|
||||
return image.copy();
|
||||
}
|
||||
case CV_8UC3: {
|
||||
cv::Mat rgb;
|
||||
cv::cvtColor(mat, rgb, cv::COLOR_BGR2RGB);
|
||||
QImage image(rgb.data, rgb.cols, rgb.rows, static_cast<int>(rgb.step), QImage::Format_RGB888);
|
||||
return image.copy();
|
||||
}
|
||||
case CV_8UC4: {
|
||||
QImage image(mat.data, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_ARGB32);
|
||||
return image.copy();
|
||||
}
|
||||
default: {
|
||||
cv::Mat converted;
|
||||
mat.convertTo(converted, CV_8U);
|
||||
return matToQImage(converted);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cv::Mat ImageConverter::qImageToMat(const QImage &image)
|
||||
{
|
||||
if (image.isNull()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const QImage converted = image.convertToFormat(QImage::Format_RGB888);
|
||||
cv::Mat rgb(converted.height(), converted.width(), CV_8UC3,
|
||||
const_cast<uchar *>(converted.bits()),
|
||||
static_cast<size_t>(converted.bytesPerLine()));
|
||||
cv::Mat bgr;
|
||||
cv::cvtColor(rgb, bgr, cv::COLOR_RGB2BGR);
|
||||
return bgr.clone();
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
#include "ImageProcessor.h"
|
||||
|
||||
#include <opencv2/imgproc.hpp>
|
||||
#include <algorithm>
|
||||
|
||||
ProcessResult ImageProcessor::rotate(const cv::Mat &source, double angleDegrees)
|
||||
{
|
||||
if (source.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const cv::Point2f center(static_cast<float>(source.cols) / 2.0F, static_cast<float>(source.rows) / 2.0F);
|
||||
cv::Mat matrix = cv::getRotationMatrix2D(center, angleDegrees, 1.0);
|
||||
|
||||
const double absCos = std::abs(matrix.at<double>(0, 0));
|
||||
const double absSin = std::abs(matrix.at<double>(0, 1));
|
||||
const int boundW = static_cast<int>(source.rows * absSin + source.cols * absCos);
|
||||
const int boundH = static_cast<int>(source.rows * absCos + source.cols * absSin);
|
||||
|
||||
matrix.at<double>(0, 2) += boundW / 2.0 - center.x;
|
||||
matrix.at<double>(1, 2) += boundH / 2.0 - center.y;
|
||||
|
||||
cv::Mat output;
|
||||
cv::warpAffine(source, output, matrix, cv::Size(boundW, boundH), cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(30, 30, 30));
|
||||
return {output, QStringLiteral("旋转 %1° 完成").arg(angleDegrees)};
|
||||
}
|
||||
|
||||
ProcessResult ImageProcessor::scale(const cv::Mat &source, double factor)
|
||||
{
|
||||
if (source.empty() || factor <= 0.0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
cv::Mat output;
|
||||
cv::resize(source, output, cv::Size(), factor, factor, factor >= 1.0 ? cv::INTER_CUBIC : cv::INTER_AREA);
|
||||
return {output, QStringLiteral("缩放 %1 倍完成,尺寸:%2 × %3").arg(factor).arg(output.cols).arg(output.rows)};
|
||||
}
|
||||
|
||||
ProcessResult ImageProcessor::translate(const cv::Mat &source, int dx, int dy)
|
||||
{
|
||||
if (source.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const cv::Mat matrix = (cv::Mat_<double>(2, 3) << 1, 0, dx, 0, 1, dy);
|
||||
cv::Mat output;
|
||||
cv::warpAffine(source, output, matrix, source.size(), cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(30, 30, 30));
|
||||
return {output, QStringLiteral("平移完成:dx=%1, dy=%2").arg(dx).arg(dy)};
|
||||
}
|
||||
|
||||
ProcessResult ImageProcessor::extractTargets(const cv::Mat &source)
|
||||
{
|
||||
if (source.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
cv::Mat gray;
|
||||
if (source.channels() == 1) {
|
||||
gray = source.clone();
|
||||
} else {
|
||||
cv::cvtColor(source, gray, cv::COLOR_BGR2GRAY);
|
||||
}
|
||||
|
||||
cv::Mat blurred;
|
||||
cv::GaussianBlur(gray, blurred, cv::Size(5, 5), 0);
|
||||
|
||||
cv::Mat binary;
|
||||
cv::threshold(blurred, 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);
|
||||
|
||||
cv::Mat output;
|
||||
if (source.channels() == 1) {
|
||||
cv::cvtColor(source, output, cv::COLOR_GRAY2BGR);
|
||||
} else {
|
||||
output = source.clone();
|
||||
}
|
||||
|
||||
int validCount = 0;
|
||||
double totalArea = 0.0;
|
||||
const double minArea = std::max(80.0, source.cols * source.rows * 0.0005);
|
||||
|
||||
for (const auto &contour : contours) {
|
||||
const double area = cv::contourArea(contour);
|
||||
if (area < minArea) {
|
||||
continue;
|
||||
}
|
||||
++validCount;
|
||||
totalArea += area;
|
||||
const cv::Rect box = cv::boundingRect(contour);
|
||||
cv::rectangle(output, box, cv::Scalar(0, 0, 255), 2);
|
||||
cv::drawContours(output, std::vector<std::vector<cv::Point>>{contour}, -1, cv::Scalar(0, 255, 0), 2);
|
||||
const cv::Moments moments = cv::moments(contour);
|
||||
if (moments.m00 != 0.0) {
|
||||
const int cx = static_cast<int>(moments.m10 / moments.m00);
|
||||
const int cy = static_cast<int>(moments.m01 / moments.m00);
|
||||
cv::circle(output, cv::Point(cx, cy), 4, cv::Scalar(255, 0, 0), -1);
|
||||
}
|
||||
}
|
||||
|
||||
return {output, QStringLiteral("目标提取完成:检测到 %1 个目标,总面积约 %2 像素")
|
||||
.arg(validCount)
|
||||
.arg(static_cast<int>(totalArea))};
|
||||
}
|
||||
|
||||
ProcessResult ImageProcessor::classifySimple(const cv::Mat &source)
|
||||
{
|
||||
if (source.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
cv::Mat hsv;
|
||||
if (source.channels() == 1) {
|
||||
cv::cvtColor(source, hsv, cv::COLOR_GRAY2BGR);
|
||||
cv::cvtColor(hsv, hsv, cv::COLOR_BGR2HSV);
|
||||
} else {
|
||||
cv::cvtColor(source, hsv, cv::COLOR_BGR2HSV);
|
||||
}
|
||||
|
||||
const cv::Scalar meanHsv = cv::mean(hsv);
|
||||
const double hue = meanHsv[0];
|
||||
const double saturation = meanHsv[1];
|
||||
const double value = meanHsv[2];
|
||||
|
||||
QString type;
|
||||
if (value < 70) {
|
||||
type = QStringLiteral("偏暗图像");
|
||||
} else if (saturation < 45) {
|
||||
type = QStringLiteral("低饱和 / 灰度感图像");
|
||||
} else if (hue < 15 || hue > 160) {
|
||||
type = QStringLiteral("红色系图像");
|
||||
} else if (hue < 45) {
|
||||
type = QStringLiteral("黄色 / 橙色系图像");
|
||||
} else if (hue < 85) {
|
||||
type = QStringLiteral("绿色系图像");
|
||||
} else if (hue < 130) {
|
||||
type = QStringLiteral("蓝色系图像");
|
||||
} else {
|
||||
type = QStringLiteral("紫色系图像");
|
||||
}
|
||||
|
||||
cv::Mat output = source.clone();
|
||||
return {output, QStringLiteral("简单分类:%1(平均 H=%2, S=%3, V=%4)")
|
||||
.arg(type)
|
||||
.arg(hue, 0, 'f', 1)
|
||||
.arg(saturation, 0, 'f', 1)
|
||||
.arg(value, 0, 'f', 1)};
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
#include "ImageView.h"
|
||||
|
||||
#include <QGraphicsPixmapItem>
|
||||
#include <QGraphicsScene>
|
||||
#include <QMouseEvent>
|
||||
#include <QPainter>
|
||||
#include <QScrollBar>
|
||||
#include <QWheelEvent>
|
||||
|
||||
ImageView::ImageView(QWidget *parent)
|
||||
: QGraphicsView(parent), scene_(new QGraphicsScene(this))
|
||||
{
|
||||
setScene(scene_);
|
||||
pixmapItem_ = scene_->addPixmap(QPixmap());
|
||||
pixmapItem_->setTransformationMode(Qt::SmoothTransformation);
|
||||
|
||||
setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
|
||||
setDragMode(QGraphicsView::ScrollHandDrag);
|
||||
setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
|
||||
setBackgroundBrush(QColor(36, 36, 36));
|
||||
setFrameShape(QFrame::StyledPanel);
|
||||
setAlignment(Qt::AlignCenter);
|
||||
}
|
||||
|
||||
void ImageView::setImage(const QImage &image)
|
||||
{
|
||||
if (image.isNull()) {
|
||||
clearImage();
|
||||
return;
|
||||
}
|
||||
|
||||
pixmap_ = QPixmap::fromImage(image);
|
||||
pixmapItem_->setPixmap(pixmap_);
|
||||
resetSceneRect();
|
||||
fitImageToView();
|
||||
}
|
||||
|
||||
void ImageView::clearImage()
|
||||
{
|
||||
pixmap_ = QPixmap();
|
||||
pixmapItem_->setPixmap(QPixmap());
|
||||
scene_->setSceneRect(QRectF());
|
||||
resetTransform();
|
||||
zoomFactor_ = 1.0;
|
||||
}
|
||||
|
||||
void ImageView::fitImageToView()
|
||||
{
|
||||
if (!hasImage()) {
|
||||
return;
|
||||
}
|
||||
resetTransform();
|
||||
fitInView(pixmapItem_, Qt::KeepAspectRatio);
|
||||
zoomFactor_ = transform().m11();
|
||||
}
|
||||
|
||||
bool ImageView::hasImage() const
|
||||
{
|
||||
return !pixmap_.isNull();
|
||||
}
|
||||
|
||||
void ImageView::wheelEvent(QWheelEvent *event)
|
||||
{
|
||||
if (!hasImage()) {
|
||||
QGraphicsView::wheelEvent(event);
|
||||
return;
|
||||
}
|
||||
|
||||
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
|
||||
const int delta = event->angleDelta().y();
|
||||
#else
|
||||
const int delta = event->delta();
|
||||
#endif
|
||||
const double factor = delta > 0 ? 1.15 : 1.0 / 1.15;
|
||||
zoomFactor_ *= factor;
|
||||
scale(factor, factor);
|
||||
event->accept();
|
||||
}
|
||||
|
||||
void ImageView::mouseDoubleClickEvent(QMouseEvent *event)
|
||||
{
|
||||
Q_UNUSED(event)
|
||||
fitImageToView();
|
||||
}
|
||||
|
||||
void ImageView::resetSceneRect()
|
||||
{
|
||||
scene_->setSceneRect(pixmap_.rect());
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
#include "ImageWorker.h"
|
||||
|
||||
void ImageWorker::process(cv::Mat image, ImageWorker::Operation operation, double value, int dx, int dy)
|
||||
{
|
||||
if (image.empty()) {
|
||||
Q_EMIT failed(QStringLiteral("没有可处理的图片"));
|
||||
return;
|
||||
}
|
||||
|
||||
ProcessResult result;
|
||||
switch (operation) {
|
||||
case Operation::Rotate:
|
||||
result = ImageProcessor::rotate(image, value);
|
||||
break;
|
||||
case Operation::Scale:
|
||||
result = ImageProcessor::scale(image, value);
|
||||
break;
|
||||
case Operation::Translate:
|
||||
result = ImageProcessor::translate(image, dx, dy);
|
||||
break;
|
||||
case Operation::ExtractTargets:
|
||||
result = ImageProcessor::extractTargets(image);
|
||||
break;
|
||||
case Operation::ClassifySimple:
|
||||
result = ImageProcessor::classifySimple(image);
|
||||
break;
|
||||
}
|
||||
|
||||
if (result.image.empty()) {
|
||||
Q_EMIT failed(QStringLiteral("图像处理失败"));
|
||||
return;
|
||||
}
|
||||
|
||||
Q_EMIT finished(result);
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
#include "MainWindow.h"
|
||||
|
||||
#include "ImageConverter.h"
|
||||
#include "ImageView.h"
|
||||
|
||||
#include <QAction>
|
||||
#include <QApplication>
|
||||
#include <QBoxLayout>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QFile>
|
||||
#include <QFileDialog>
|
||||
#include <QFileInfo>
|
||||
#include <QGroupBox>
|
||||
#include <QLabel>
|
||||
#include <QMenuBar>
|
||||
#include <QMessageBox>
|
||||
#include <QPushButton>
|
||||
#include <QSpinBox>
|
||||
#include <QSplitter>
|
||||
#include <QStatusBar>
|
||||
#include <QToolBar>
|
||||
#include <QWidget>
|
||||
#include <opencv2/imgcodecs.hpp>
|
||||
|
||||
MainWindow::MainWindow(QWidget *parent)
|
||||
: QMainWindow(parent)
|
||||
{
|
||||
qRegisterMetaType<ProcessResult>("ProcessResult");
|
||||
qRegisterMetaType<ImageWorker::Operation>("ImageWorker::Operation");
|
||||
qRegisterMetaType<cv::Mat>("cv::Mat");
|
||||
|
||||
buildUi();
|
||||
setupWorkerThread();
|
||||
setWindowTitle(QStringLiteral("chengnan - Qt/OpenCV 图像处理"));
|
||||
}
|
||||
|
||||
MainWindow::~MainWindow()
|
||||
{
|
||||
workerThread_.quit();
|
||||
workerThread_.wait();
|
||||
}
|
||||
|
||||
void MainWindow::buildUi()
|
||||
{
|
||||
auto *openAction = new QAction(QStringLiteral("打开图片"), this);
|
||||
saveAction_ = new QAction(QStringLiteral("保存图片"), this);
|
||||
saveAsAction_ = new QAction(QStringLiteral("另存图片"), this);
|
||||
auto *resetAction = new QAction(QStringLiteral("还原原图"), this);
|
||||
auto *exitAction = new QAction(QStringLiteral("退出"), this);
|
||||
|
||||
connect(openAction, &QAction::triggered, this, &MainWindow::openImage);
|
||||
connect(saveAction_, &QAction::triggered, this, &MainWindow::saveImage);
|
||||
connect(saveAsAction_, &QAction::triggered, this, &MainWindow::saveImageAs);
|
||||
connect(resetAction, &QAction::triggered, this, &MainWindow::resetToOriginal);
|
||||
connect(exitAction, &QAction::triggered, qApp, &QApplication::quit);
|
||||
|
||||
auto *fileMenu = menuBar()->addMenu(QStringLiteral("文件"));
|
||||
fileMenu->addAction(openAction);
|
||||
fileMenu->addAction(saveAction_);
|
||||
fileMenu->addAction(saveAsAction_);
|
||||
fileMenu->addSeparator();
|
||||
fileMenu->addAction(exitAction);
|
||||
|
||||
auto *editMenu = menuBar()->addMenu(QStringLiteral("处理"));
|
||||
editMenu->addAction(resetAction);
|
||||
|
||||
auto *toolbar = addToolBar(QStringLiteral("主工具栏"));
|
||||
toolbar->addAction(openAction);
|
||||
toolbar->addAction(saveAction_);
|
||||
toolbar->addAction(saveAsAction_);
|
||||
toolbar->addAction(resetAction);
|
||||
|
||||
originalView_ = new ImageView(this);
|
||||
processedView_ = new ImageView(this);
|
||||
|
||||
auto *leftBox = new QGroupBox(QStringLiteral("处理前图像"), this);
|
||||
auto *leftLayout = new QVBoxLayout(leftBox);
|
||||
leftLayout->addWidget(originalView_);
|
||||
|
||||
auto *rightBox = new QGroupBox(QStringLiteral("处理后图像"), this);
|
||||
auto *rightLayout = new QVBoxLayout(rightBox);
|
||||
rightLayout->addWidget(processedView_);
|
||||
|
||||
auto *splitter = new QSplitter(Qt::Horizontal, this);
|
||||
splitter->addWidget(leftBox);
|
||||
splitter->addWidget(rightBox);
|
||||
splitter->setStretchFactor(0, 1);
|
||||
splitter->setStretchFactor(1, 1);
|
||||
|
||||
scaleSpin_ = new QDoubleSpinBox(this);
|
||||
scaleSpin_->setRange(0.1, 5.0);
|
||||
scaleSpin_->setSingleStep(0.1);
|
||||
scaleSpin_->setValue(1.25);
|
||||
scaleSpin_->setSuffix(QStringLiteral(" 倍"));
|
||||
|
||||
angleSpin_ = new QDoubleSpinBox(this);
|
||||
angleSpin_->setRange(-360.0, 360.0);
|
||||
angleSpin_->setSingleStep(5.0);
|
||||
angleSpin_->setValue(90.0);
|
||||
angleSpin_->setSuffix(QStringLiteral("°"));
|
||||
|
||||
translateSpin_ = new QSpinBox(this);
|
||||
translateSpin_->setRange(1, 1000);
|
||||
translateSpin_->setValue(40);
|
||||
translateSpin_->setSuffix(QStringLiteral(" px"));
|
||||
|
||||
auto *scaleUpButton = new QPushButton(QStringLiteral("放大"), this);
|
||||
auto *scaleDownButton = new QPushButton(QStringLiteral("缩小"), this);
|
||||
auto *rotateLeftButton = new QPushButton(QStringLiteral("逆时针旋转"), this);
|
||||
auto *rotateRightButton = new QPushButton(QStringLiteral("顺时针旋转"), this);
|
||||
auto *upButton = new QPushButton(QStringLiteral("上移"), this);
|
||||
auto *downButton = new QPushButton(QStringLiteral("下移"), this);
|
||||
auto *leftButton = new QPushButton(QStringLiteral("左移"), this);
|
||||
auto *rightButton = new QPushButton(QStringLiteral("右移"), this);
|
||||
auto *extractButton = new QPushButton(QStringLiteral("目标提取"), this);
|
||||
auto *classifyButton = new QPushButton(QStringLiteral("简单分类"), this);
|
||||
|
||||
connect(scaleUpButton, &QPushButton::clicked, this, &MainWindow::scaleUp);
|
||||
connect(scaleDownButton, &QPushButton::clicked, this, &MainWindow::scaleDown);
|
||||
connect(rotateLeftButton, &QPushButton::clicked, this, &MainWindow::rotateLeft);
|
||||
connect(rotateRightButton, &QPushButton::clicked, this, &MainWindow::rotateRight);
|
||||
connect(upButton, &QPushButton::clicked, this, &MainWindow::translateUp);
|
||||
connect(downButton, &QPushButton::clicked, this, &MainWindow::translateDown);
|
||||
connect(leftButton, &QPushButton::clicked, this, &MainWindow::translateLeft);
|
||||
connect(rightButton, &QPushButton::clicked, this, &MainWindow::translateRight);
|
||||
connect(extractButton, &QPushButton::clicked, this, &MainWindow::extractTargets);
|
||||
connect(classifyButton, &QPushButton::clicked, this, &MainWindow::classifyImage);
|
||||
|
||||
auto *controlBox = new QGroupBox(QStringLiteral("图像处理操作"), this);
|
||||
auto *controlLayout = new QHBoxLayout(controlBox);
|
||||
controlLayout->addWidget(new QLabel(QStringLiteral("缩放比例:"), this));
|
||||
controlLayout->addWidget(scaleSpin_);
|
||||
controlLayout->addWidget(scaleUpButton);
|
||||
controlLayout->addWidget(scaleDownButton);
|
||||
controlLayout->addSpacing(12);
|
||||
controlLayout->addWidget(new QLabel(QStringLiteral("旋转角度:"), this));
|
||||
controlLayout->addWidget(angleSpin_);
|
||||
controlLayout->addWidget(rotateLeftButton);
|
||||
controlLayout->addWidget(rotateRightButton);
|
||||
controlLayout->addSpacing(12);
|
||||
controlLayout->addWidget(new QLabel(QStringLiteral("平移距离:"), this));
|
||||
controlLayout->addWidget(translateSpin_);
|
||||
controlLayout->addWidget(upButton);
|
||||
controlLayout->addWidget(downButton);
|
||||
controlLayout->addWidget(leftButton);
|
||||
controlLayout->addWidget(rightButton);
|
||||
controlLayout->addSpacing(12);
|
||||
controlLayout->addWidget(extractButton);
|
||||
controlLayout->addWidget(classifyButton);
|
||||
controlLayout->addStretch(1);
|
||||
|
||||
infoLabel_ = new QLabel(QStringLiteral("请打开一张图片开始处理。提示:鼠标滚轮可缩放视图,双击图片可适配窗口。"), this);
|
||||
infoLabel_->setWordWrap(true);
|
||||
|
||||
auto *central = new QWidget(this);
|
||||
auto *mainLayout = new QVBoxLayout(central);
|
||||
mainLayout->addWidget(splitter, 1);
|
||||
mainLayout->addWidget(controlBox);
|
||||
mainLayout->addWidget(infoLabel_);
|
||||
setCentralWidget(central);
|
||||
|
||||
statusLabel_ = new QLabel(QStringLiteral("就绪"), this);
|
||||
statusBar()->addPermanentWidget(statusLabel_, 1);
|
||||
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
void MainWindow::setupWorkerThread()
|
||||
{
|
||||
worker_ = new ImageWorker();
|
||||
worker_->moveToThread(&workerThread_);
|
||||
|
||||
connect(&workerThread_, &QThread::finished, worker_, &QObject::deleteLater);
|
||||
connect(this, &MainWindow::processRequested, worker_, &ImageWorker::process, Qt::QueuedConnection);
|
||||
connect(worker_, &ImageWorker::finished, this, &MainWindow::onProcessFinished, Qt::QueuedConnection);
|
||||
connect(worker_, &ImageWorker::failed, this, &MainWindow::onProcessFailed, Qt::QueuedConnection);
|
||||
|
||||
workerThread_.start();
|
||||
}
|
||||
|
||||
void MainWindow::openImage()
|
||||
{
|
||||
const QString path = QFileDialog::getOpenFileName(
|
||||
this,
|
||||
QStringLiteral("打开图片"),
|
||||
QString(),
|
||||
QStringLiteral("图片文件 (*.png *.jpg *.jpeg *.bmp *.tif *.tiff);;所有文件 (*.*)"));
|
||||
if (path.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string localPath = QFile::encodeName(path).toStdString();
|
||||
cv::Mat image = cv::imread(localPath, cv::IMREAD_COLOR);
|
||||
if (image.empty()) {
|
||||
QMessageBox::warning(this, QStringLiteral("打开失败"), QStringLiteral("无法读取图片:%1").arg(path));
|
||||
return;
|
||||
}
|
||||
|
||||
originalImage_ = image;
|
||||
processedImage_ = image.clone();
|
||||
currentPath_ = path;
|
||||
updateViews();
|
||||
infoLabel_->setText(QStringLiteral("已打开:%1,尺寸:%2 × %3")
|
||||
.arg(QFileInfo(path).fileName())
|
||||
.arg(image.cols)
|
||||
.arg(image.rows));
|
||||
statusLabel_->setText(QStringLiteral("已打开图片"));
|
||||
}
|
||||
|
||||
void MainWindow::saveImage()
|
||||
{
|
||||
if (!ensureHasImage()) {
|
||||
return;
|
||||
}
|
||||
if (currentPath_.isEmpty()) {
|
||||
saveImageAs();
|
||||
return;
|
||||
}
|
||||
writeCurrentImageTo(currentPath_);
|
||||
}
|
||||
|
||||
void MainWindow::saveImageAs()
|
||||
{
|
||||
if (!ensureHasImage()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const QString path = QFileDialog::getSaveFileName(
|
||||
this,
|
||||
QStringLiteral("另存图片"),
|
||||
currentPath_.isEmpty() ? QStringLiteral("processed.png") : currentPath_,
|
||||
QStringLiteral("PNG 图片 (*.png);;JPEG 图片 (*.jpg *.jpeg);;BMP 图片 (*.bmp);;所有文件 (*.*)"));
|
||||
if (path.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (writeCurrentImageTo(path)) {
|
||||
currentPath_ = path;
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::resetToOriginal()
|
||||
{
|
||||
if (!ensureHasImage()) {
|
||||
return;
|
||||
}
|
||||
processedImage_ = originalImage_.clone();
|
||||
updateViews();
|
||||
infoLabel_->setText(QStringLiteral("已还原为原始图片"));
|
||||
}
|
||||
|
||||
void MainWindow::onProcessFinished(ProcessResult result)
|
||||
{
|
||||
processedImage_ = result.image;
|
||||
updateViews();
|
||||
infoLabel_->setText(result.description);
|
||||
statusLabel_->setText(QStringLiteral("处理完成"));
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
void MainWindow::onProcessFailed(const QString &message)
|
||||
{
|
||||
QMessageBox::warning(this, QStringLiteral("处理失败"), message);
|
||||
statusLabel_->setText(QStringLiteral("处理失败"));
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
void MainWindow::rotateLeft()
|
||||
{
|
||||
requestProcess(ImageWorker::Operation::Rotate, -angleSpin_->value());
|
||||
}
|
||||
|
||||
void MainWindow::rotateRight()
|
||||
{
|
||||
requestProcess(ImageWorker::Operation::Rotate, angleSpin_->value());
|
||||
}
|
||||
|
||||
void MainWindow::scaleUp()
|
||||
{
|
||||
requestProcess(ImageWorker::Operation::Scale, scaleSpin_->value());
|
||||
}
|
||||
|
||||
void MainWindow::scaleDown()
|
||||
{
|
||||
requestProcess(ImageWorker::Operation::Scale, 1.0 / scaleSpin_->value());
|
||||
}
|
||||
|
||||
void MainWindow::translateUp()
|
||||
{
|
||||
requestProcess(ImageWorker::Operation::Translate, 0.0, 0, -translateSpin_->value());
|
||||
}
|
||||
|
||||
void MainWindow::translateDown()
|
||||
{
|
||||
requestProcess(ImageWorker::Operation::Translate, 0.0, 0, translateSpin_->value());
|
||||
}
|
||||
|
||||
void MainWindow::translateLeft()
|
||||
{
|
||||
requestProcess(ImageWorker::Operation::Translate, 0.0, -translateSpin_->value(), 0);
|
||||
}
|
||||
|
||||
void MainWindow::translateRight()
|
||||
{
|
||||
requestProcess(ImageWorker::Operation::Translate, 0.0, translateSpin_->value(), 0);
|
||||
}
|
||||
|
||||
void MainWindow::extractTargets()
|
||||
{
|
||||
requestProcess(ImageWorker::Operation::ExtractTargets);
|
||||
}
|
||||
|
||||
void MainWindow::classifyImage()
|
||||
{
|
||||
requestProcess(ImageWorker::Operation::ClassifySimple);
|
||||
}
|
||||
|
||||
void MainWindow::updateViews()
|
||||
{
|
||||
originalView_->setImage(ImageConverter::matToQImage(originalImage_));
|
||||
processedView_->setImage(ImageConverter::matToQImage(processedImage_));
|
||||
}
|
||||
|
||||
void MainWindow::setBusy(bool busy)
|
||||
{
|
||||
busy_ = busy;
|
||||
saveAction_->setEnabled(!busy && !processedImage_.empty());
|
||||
saveAsAction_->setEnabled(!busy && !processedImage_.empty());
|
||||
if (busy) {
|
||||
statusLabel_->setText(QStringLiteral("处理中..."));
|
||||
}
|
||||
}
|
||||
|
||||
bool MainWindow::ensureHasImage() const
|
||||
{
|
||||
if (processedImage_.empty()) {
|
||||
QMessageBox::information(const_cast<MainWindow *>(this), QStringLiteral("提示"), QStringLiteral("请先打开图片。"));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void MainWindow::requestProcess(ImageWorker::Operation operation, double value, int dx, int dy)
|
||||
{
|
||||
if (busy_) {
|
||||
return;
|
||||
}
|
||||
if (!ensureHasImage()) {
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
Q_EMIT processRequested(processedImage_.clone(), operation, value, dx, dy);
|
||||
}
|
||||
|
||||
bool MainWindow::writeCurrentImageTo(const QString &path)
|
||||
{
|
||||
if (processedImage_.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string localPath = QFile::encodeName(path).toStdString();
|
||||
if (!cv::imwrite(localPath, processedImage_)) {
|
||||
QMessageBox::warning(this, QStringLiteral("保存失败"), QStringLiteral("无法保存图片:%1").arg(path));
|
||||
return false;
|
||||
}
|
||||
|
||||
statusLabel_->setText(QStringLiteral("已保存图片"));
|
||||
infoLabel_->setText(QStringLiteral("已保存处理后图片:%1").arg(path));
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#include <QApplication>
|
||||
#include <QMetaType>
|
||||
|
||||
#include "MainWindow.h"
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
QApplication app(argc, argv);
|
||||
QApplication::setApplicationName("chengnan");
|
||||
QApplication::setOrganizationName("luochen570");
|
||||
QApplication::setApplicationVersion(CHENGNAN_APP_VERSION);
|
||||
|
||||
qRegisterMetaType<cv::Mat>("cv::Mat");
|
||||
|
||||
MainWindow window;
|
||||
window.resize(1280, 760);
|
||||
window.show();
|
||||
|
||||
return QApplication::exec();
|
||||
}
|
||||
@@ -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)
|
||||
@@ -1,14 +0,0 @@
|
||||
#include "MainWindow.h"
|
||||
|
||||
#include <QApplication>
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
QApplication app(argc, argv);
|
||||
|
||||
MainWindow window;
|
||||
window.resize(1180, 760);
|
||||
window.show();
|
||||
|
||||
return app.exec();
|
||||
}
|
||||
@@ -1,297 +0,0 @@
|
||||
# Qt + OpenCV 图像显示与处理
|
||||
|
||||
本工程使用 Qt Widgets 设计界面,使用 OpenCV 完成图像处理。程序支持打开图片、保存图片、另存图片,支持缩放、平移、旋转,并提供目标提取和简单图像分类功能。图像显示使用 Qt 的 `QLabel`/`QWidget`,没有使用 `cv::imshow`。
|
||||
|
||||
## 文件说明
|
||||
|
||||
- `CMakeLists.txt`:CMake 工程配置。
|
||||
- `main.cpp`:程序入口。
|
||||
- `MainWindow.h`:主窗口类和处理参数声明。
|
||||
- `MainWindow.cpp`:界面、图像读写、Qt 线程和 OpenCV 处理实现。
|
||||
|
||||
## 功能
|
||||
|
||||
- 打开图片:读取 `png/jpg/bmp/tif` 等常见格式。
|
||||
- 保存图片:保存当前处理结果。
|
||||
- 另存图片:将处理结果保存为新文件。
|
||||
- 显示对比:左侧显示处理前图像,右侧显示处理后图像。
|
||||
- 基本处理:缩放、水平平移、垂直平移、旋转。
|
||||
- 目标提取:使用灰度化、Otsu 阈值、形态学处理和轮廓检测提取前景目标,并用绿色矩形框标记目标。
|
||||
- 图像分类:根据平均亮度和主色通道给出简单分类,同时显示目标数量。
|
||||
- 线程处理:图像处理工作对象运行在 `QThread` 中,避免阻塞界面。
|
||||
|
||||
## Windows 构建说明
|
||||
|
||||
本工程使用 CMake 管理,目标是构建 Windows 桌面应用程序 `QtOpenCVImageTool.exe`。推荐使用 **MSVC 64 位**,因为 OpenCV 官方 Windows 预编译包通常就是 MSVC 版本,配置最省事。
|
||||
|
||||
构建时请保持三者一致:
|
||||
|
||||
- 编译器一致:MSVC 对 MSVC,MinGW 对 MinGW。
|
||||
- 位数一致:建议全部使用 64 位。
|
||||
- Qt、OpenCV、CMake 使用同一套构建环境。
|
||||
|
||||
如果使用 MSVC,则不要混用 MinGW 版 Qt;如果使用 MinGW,则不要直接使用 OpenCV 官方 MSVC 预编译包。
|
||||
|
||||
### 需要安装的软件
|
||||
|
||||
1. Visual Studio 2022 或 Visual Studio 2022 Build Tools
|
||||
|
||||
安装时勾选:
|
||||
|
||||
```text
|
||||
Desktop development with C++
|
||||
MSVC v143 x64/x86 build tools
|
||||
Windows 10 SDK 或 Windows 11 SDK
|
||||
C++ CMake tools for Windows
|
||||
```
|
||||
|
||||
安装完成后,系统中应能找到类似路径:
|
||||
|
||||
```text
|
||||
C:\Program Files\Microsoft Visual Studio\2022\Community
|
||||
C:\Program Files\Microsoft Visual Studio\2022\BuildTools
|
||||
```
|
||||
|
||||
2. Qt for Windows
|
||||
|
||||
使用 Qt Online Installer 安装 Qt。推荐安装 Qt 6.x,并勾选 MSVC 64 位组件,例如:
|
||||
|
||||
```text
|
||||
Qt 6.6.x
|
||||
MSVC 2019 64-bit 或 MSVC 2022 64-bit
|
||||
Qt Creator
|
||||
```
|
||||
|
||||
安装完成后,Qt 路径通常类似:
|
||||
|
||||
```text
|
||||
C:\Qt\6.6.0\msvc2019_64
|
||||
C:\Qt\6.6.0\msvc2022_64
|
||||
```
|
||||
|
||||
该目录下应存在:
|
||||
|
||||
```text
|
||||
C:\Qt\6.6.0\msvc2019_64\lib\cmake\Qt6\Qt6Config.cmake
|
||||
```
|
||||
|
||||
3. OpenCV for Windows
|
||||
|
||||
可以使用 OpenCV 官方 Windows 包。解压或安装到例如:
|
||||
|
||||
```text
|
||||
C:\opencv
|
||||
```
|
||||
|
||||
常见的 CMake 配置路径是:
|
||||
|
||||
```text
|
||||
C:\opencv\build\x64\vc16\lib
|
||||
```
|
||||
|
||||
该目录下应存在:
|
||||
|
||||
```text
|
||||
C:\opencv\build\x64\vc16\lib\OpenCVConfig.cmake
|
||||
```
|
||||
|
||||
4. CMake
|
||||
|
||||
如果安装 Visual Studio 时勾选了 CMake 工具,通常已经够用。也可以单独安装 CMake for Windows。命令行检查:
|
||||
|
||||
```bat
|
||||
cmake --version
|
||||
```
|
||||
|
||||
### 推荐方式:Qt Creator 构建
|
||||
|
||||
1. 打开 Qt Creator。
|
||||
2. 选择“打开项目”,打开本目录的 `CMakeLists.txt`。
|
||||
3. 选择 Windows Kit,例如:
|
||||
|
||||
```text
|
||||
Desktop Qt 6.x.x MSVC 2019 64-bit
|
||||
Desktop Qt 6.x.x MSVC 2022 64-bit
|
||||
```
|
||||
|
||||
4. 如果 CMake 找不到 OpenCV,在 Qt Creator 的 CMake 配置项中添加:
|
||||
|
||||
```text
|
||||
OpenCV_DIR=C:/opencv/build/x64/vc16/lib
|
||||
```
|
||||
|
||||
5. 配置完成后点击“构建”。
|
||||
6. 构建成功后会生成 `QtOpenCVImageTool.exe`。
|
||||
7. 在 Qt Creator 中点击“运行”即可启动程序。
|
||||
|
||||
### 命令行构建:MSVC
|
||||
|
||||
打开开始菜单中的:
|
||||
|
||||
```text
|
||||
x64 Native Tools Command Prompt for VS 2022
|
||||
```
|
||||
|
||||
进入工程目录,例如:
|
||||
|
||||
```bat
|
||||
cd /d D:\QtOpenCVImageTool
|
||||
```
|
||||
|
||||
使用项目提供的脚本构建:
|
||||
|
||||
```bat
|
||||
build_windows.bat C:\Qt\6.6.0\msvc2019_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
|
||||
```
|
||||
|
||||
如果你的 Qt 是 MSVC 2022 版本,路径可改为:
|
||||
|
||||
```bat
|
||||
build_windows.bat C:\Qt\6.6.0\msvc2022_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
|
||||
```
|
||||
|
||||
也可以手动执行 CMake:
|
||||
|
||||
```bat
|
||||
mkdir build-windows
|
||||
cd build-windows
|
||||
cmake .. -G "Visual Studio 17 2022" -A x64 -DCMAKE_PREFIX_PATH=C:\Qt\6.6.0\msvc2019_64 -DOpenCV_DIR=C:\opencv\build\x64\vc16\lib
|
||||
cmake --build . --config Release
|
||||
```
|
||||
|
||||
MSVC 生成的 exe 通常位于:
|
||||
|
||||
```text
|
||||
build-windows\Release\QtOpenCVImageTool.exe
|
||||
```
|
||||
|
||||
### 命令行构建:MinGW
|
||||
|
||||
如果使用 MinGW,需要安装 MinGW 版 Qt,并准备 MinGW 编译出来的 OpenCV。不要把 MSVC 版 OpenCV 直接给 MinGW 使用。
|
||||
|
||||
示例:
|
||||
|
||||
```bat
|
||||
build_windows.bat C:\Qt\6.6.0\mingw_64 C:\opencv-mingw\install "MinGW Makefiles"
|
||||
```
|
||||
|
||||
手动构建:
|
||||
|
||||
```bat
|
||||
mkdir build-windows
|
||||
cd build-windows
|
||||
cmake .. -G "MinGW Makefiles" -DCMAKE_PREFIX_PATH=C:\Qt\6.6.0\mingw_64 -DOpenCV_DIR=C:\opencv-mingw\install
|
||||
cmake --build . --config Release
|
||||
```
|
||||
|
||||
MinGW 生成的 exe 通常位于:
|
||||
|
||||
```text
|
||||
build-windows\QtOpenCVImageTool.exe
|
||||
```
|
||||
|
||||
### 运行和发布
|
||||
|
||||
构建出来的 `QtOpenCVImageTool.exe` 运行时需要 Qt 和 OpenCV 的 DLL。开发阶段可以直接在 Qt Creator 中运行;如果要单独拷贝给别人运行,需要把依赖 DLL 一起放到 exe 目录。
|
||||
|
||||
MSVC Release 示例:
|
||||
|
||||
```bat
|
||||
cd build-windows\Release
|
||||
C:\Qt\6.6.0\msvc2019_64\bin\windeployqt.exe QtOpenCVImageTool.exe
|
||||
copy C:\opencv\build\x64\vc16\bin\opencv_world*.dll .
|
||||
```
|
||||
|
||||
如果 OpenCV 不是 `opencv_world*.dll`,则复制对应的 `opencv_*.dll` 到 exe 所在目录。
|
||||
|
||||
MinGW 示例:
|
||||
|
||||
```bat
|
||||
cd build-windows
|
||||
C:\Qt\6.6.0\mingw_64\bin\windeployqt.exe QtOpenCVImageTool.exe
|
||||
copy C:\opencv-mingw\bin\opencv_*.dll .
|
||||
```
|
||||
|
||||
### 常见问题
|
||||
|
||||
1. `Could not find Qt6`
|
||||
|
||||
说明 `CMAKE_PREFIX_PATH` 没有指向 Qt 安装目录。请确认路径类似:
|
||||
|
||||
```text
|
||||
C:\Qt\6.6.0\msvc2019_64
|
||||
```
|
||||
|
||||
2. `Could not find OpenCV`
|
||||
|
||||
说明 `OpenCV_DIR` 没有指向包含 `OpenCVConfig.cmake` 的目录。请搜索 `OpenCVConfig.cmake`,并把它所在目录传给 CMake。
|
||||
|
||||
3. 程序启动时报缺少 DLL
|
||||
|
||||
请运行 `windeployqt`,并把 OpenCV 的 DLL 复制到 exe 所在目录。
|
||||
|
||||
4. 链接时报 MSVC/MinGW 相关错误
|
||||
|
||||
通常是 Qt、OpenCV、编译器不匹配。MSVC 工程必须使用 MSVC 版 Qt 和 MSVC 版 OpenCV;MinGW 工程必须使用 MinGW 版 Qt 和 MinGW 版 OpenCV。
|
||||
|
||||
## 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 或传统机器学习模型。
|
||||
Reference in New Issue
Block a user