Embedded_game/qianrushi/感兴趣区域提取2.py

68 lines
2.3 KiB
Python
Raw Permalink Normal View History

2025-01-02 12:48:11 +08:00
# -*- coding: utf-8 -*-
# @Time : 2024/4/15 9:39
# @Author : len
# @File : 感兴趣区域提取2.py
# @Software: PyCharm
# @Comment :
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
# 定义一个调整后的图像处理函数来改善屏幕检测
def process_image_adjusted(image_path):
# 加载图片
image = cv2.imread(image_path)
# 将图片转换成灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 应用高斯模糊,减少噪点,提升边缘检测效果
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# 自适应阈值化创建二值图像
threshold = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 11, 2)
# 从阈值化的图像中找轮廓
contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 根据轮廓面积排序,并移除面积较小的轮廓
contours = sorted(contours, key=cv2.contourArea, reverse=True)
large_contours = [cnt for cnt in contours if cv2.contourArea(cnt) > 1000]
screen_contour = None
for contour in large_contours:
# 将轮廓近似为多边形
perimeter = cv2.arcLength(contour, True)
approximation = cv2.approxPolyDP(contour, 0.02 * perimeter, True)
# 如果多边形有4条边我们假设它是屏幕
if len(approximation) == 4:
screen_contour = approximation
break
# 在图片上绘制轮廓
if screen_contour is not None:
cv2.drawContours(image, [screen_contour], -1, (0, 255, 0), 3)
screen_image = cv2.polylines(image, [screen_contour], True, (0, 255, 0), 3)
else:
screen_image = image
# 展示结果
plt.imshow(cv2.cvtColor(screen_image, cv2.COLOR_BGR2RGB))
plt.title('调整后的屏幕检测')
plt.axis('off') # 关闭坐标轴显示
plt.show()
# 设置文件夹路径
folder_path = './data/pingmu' # 将此路径替换为你的图片文件夹路径
# 遍历文件夹中的所有文件
for filename in os.listdir(folder_path):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')): # 检查文件扩展名
file_path = os.path.join(folder_path, filename) # 获取文件完整路径
process_image_adjusted(file_path)