python免费好用,但是涉及到界面就比较麻烦了,这点不如matlab好用。最近了解到PysimpleGUI,看了一下教程,简化了很多,对于一般简单应用应该够用了,从今天开始,记录一下学习过程。
图像实时处理显示例程:PySimpleGUI+Opencv(2020.12.13) - 知乎 (zhihu.com)
首先安装环境 pip inatall PySimpleGUI
然后把代码拷贝到文件里,不用修改直接可以运行,电脑得有摄像头可用才行。但是这个例程关闭的时候,仍然会占用摄像头,其它程序就无法在用了,显然这是没有释放摄像头,因为调用摄像头采用的是opencv,就简单查了一下释放摄像头的方法,有人说是cap.release(),但测试后不行。我觉得还是试试比较好,我实在判断关闭程序后,break前加入这个命令,再次运行后关闭,摄像头就释放了。下面代码是我更改过的
import PySimpleGUI as sg
import cv2
import numpy as np
def main():
sg.theme('LightGreen')
# define the window layout
layout = [
[sg.Text('OpenCV Demo', size=(60, 1), justification='center')],
[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('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))]
]
# create the window and show it without the plot
window = sg.Window('OpenCV Integration', layout, location=(800, 400))
cap = cv2.VideoCapture(0)
while True:
event, values = window.read(timeout=20)
if event == 'Exit' or event == sg.WIN_CLOSED:
cap.release()
break
ret, frame = cap.read()
if values['-THRESH-']:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)[:, :, 0]
frame = cv2.threshold(frame, values['-THRESH SLIDER-'], 255, cv2.THRESH_BINARY)[1]
elif values['-CANNY-']:
frame = cv2.Canny(frame, values['-CANNY SLIDER A-'], values['-CANNY SLIDER B-'])
elif values['-BLUR-']:
frame = cv2.GaussianBlur(frame, (21, 21), values['-BLUR SLIDER-'])
elif values['-HUE-']:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
frame[:, :, 0] += int(values['-HUE SLIDER-'])
frame = cv2.cvtColor(frame, cv2.COLOR_HSV2BGR)
elif 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)
imgbytes = cv2.imencode('.png', frame)[1].tobytes()
window['-IMAGE-'].update(data=imgbytes)
window.close()
main()