本文来自博客专栏《Python》
本专栏专注于Python项目实战开发应用
初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试有一定帮助,项目演示效果如下:
import PySimpleGUI as sg #pip install pysimplegui
import cv2 #pip install opencv-python
import numpy as np #pip install numpy
#背景色
sg.theme('LightGreen')
#定义窗口布局
layout = [
[sg.Image(filename='', key='image')],
[sg.Radio('None', 'Radio', True, size=(10, 1))],
[sg.Radio('threshold', 'Radio', size=(10, 1), key='thresh'),
sg.Slider((0, 255), 128, 1, orientation='h', size=(40, 15), key='thresh_slider')],
[sg.Radio('canny', 'Radio', size=(10, 1), key='canny'),
sg.Slider((0, 255), 128, 1, orientation='h', size=(20, 15), key='canny_slider_a'),
sg.Slider((0, 255), 128, 1, orientation='h', size=(20, 15), key='canny_slider_b')],
[sg.Radio('contour', 'Radio', size=(10, 1), key='contour'),
sg.Slider((0, 255), 128, 1, orientation='h', size=(20, 15), key='contour_slider'),
sg.Slider((0, 255), 80, 1, orientation='h', size=(20, 15), key='base_slider')],
[sg.Radio('blur', 'Radio', size=(10, 1), key='blur'),
sg.Slider((1, 11), 1, 1, orientation='h', size=(40, 15), key='blur_slider')],
[sg.Radio('hue', 'Radio', size=(10, 1), key='hue'),
sg.Slider((0, 225), 0, 1, orientation='h', size=(40, 15), key='hue_slider')],
[sg.Radio('enhance', 'Radio', size=(10, 1), key='enhance'),
sg.Slider((1, 255), 128, 1, orientation='h', size=(40, 15), key='enhance_slider')],
[sg.Button('Exit', size=(10, 1))]
]
#窗口设计
window = sg.Window('OpenCV实时图像处理',
layout,
location=(800, 400),
finalize=True)
if values['thresh']:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)[:, :, 0]
frame = cv2.threshold(frame, values['thresh_slider'], 255, cv2.THRESH_BINARY)[1]
if values['canny']:
frame = cv2.Canny(frame, values['canny_slider_a'], values['canny_slider_b'])
if values['contour']:
hue = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
hue = cv2.GaussianBlur(hue, (21, 21), 1)
hue = cv2.inRange(hue, np.array([values['contour_slider'], values['base_slider'], 40]),
np.array([values['contour_slider'] + 30, 255, 220]))
cnts= cv2.findContours(hue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
cv2.drawContours(frame, cnts, -1, (0, 0, 255), 2)
if values['blur']:
frame = cv2.GaussianBlur(frame, (21, 21), values['blur_slider'])
if values['hue']: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) frame[:, :, 0] += int(values['hue_slider']) frame = cv2.cvtColor(frame, cv2.COLOR_HSV2BGR)
if values['enhance']:
enh_val = values['enhance_slider'] / 40
clahe = cv2.createCLAHE(clipLimit=enh_val, tileGridSize=(8, 8))
lab = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)
lab[:, :, 0] = clahe.apply(lab[:, :, 0])
frame = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
if event == 'Exit' or event is None:
break
本文来自博客专栏《Python》 扫码订阅专栏
专栏介绍以及亮点
本专栏主要介绍Python项目实战开发应用,实际教程聚焦于功能,覆盖了基本的创建应用、构建和封装库。实例丰富,大量的技巧提示与图文解析,和详细的代码注解,帮助学习者快速领悟Python编程思想和掌握Python编程的核心知识,全面提升学习者学习Python语言在不同领域的实战应用技能。