Trackbar HSV OpenCv Tkinter Python
我正在创建一个使用Tkinter OpenCV Python检测对象的程序。 我已经创建了带有轨迹栏的界面,并且上传了图像,但是在更改轨迹栏的值时,图像中没有更新Trackbar HSV OpenCv Tkinter Python,python,opencv,tkinter,hsv,trackbar,Python,Opencv,Tkinter,Hsv,Trackbar,我正在创建一个使用Tkinter OpenCV Python检测对象的程序。 我已经创建了带有轨迹栏的界面,并且上传了图像,但是在更改轨迹栏的值时,图像中没有更新 from Tkinter import * # Para Interfaz Grafica import Tkinter import gtk # Para Obtener Ancho/Alto import tkFileDialog # Para
from Tkinter import * # Para Interfaz Grafica
import Tkinter
import gtk # Para Obtener Ancho/Alto
import tkFileDialog # Para Buscar Archivo
import cv2 # Libreria OpenCV
from PIL import Image, ImageTk
import numpy as np
#*******************************************************************
#Se crea la Pantalla Principal, tomando el Ancho/Alto de la Pantalla
#Se captura el ancho y alto
width = gtk.gdk.screen_width()
height = gtk.gdk.screen_height()
app = Tk()
#app.config(bg="red") # Le da color al fondo
app.geometry(str(width)+"x"+str(height)) # Cambia el tamaño de la ventana
app.title("TEST")
#*******************************************************************
#Buscar Imagen
def select_image():
# open a file chooser dialog and allow the user to select an input
# image
path = tkFileDialog.askopenfilename()
if len(path) > 0: # Si se ha cargado la imagen
# cargar imagen del disco
image = cv2.imread(path,1)
data = image.shape
# OpenCV representa imagenes en BGR ; sin embargo PIL representa
# imagenes en RGB , es necesario intercambiar los canales
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lw_range = np.array([0, 0, 0])
up_range = np.array([255, 255, 255])
mask = cv2.inRange(hsv, lw_range, up_range)
res = cv2.bitwise_and(image,image, mask= mask)
# convertir la imagen a formato PIL
image = Image.fromarray(res).resize((570,570),Image.ANTIALIAS)
# ...Luego a formato ImageTk
image=ImageTk.PhotoImage(image)
label_img = Label(app, image = image,relief=SOLID)
label_img.image=image
label_img.pack()
label_img.place(x=790,y=5)
label1 = Label(app, text="Informacion Imagen\nAlto:{}\nAncho:{}\nCanales:{}".format(data[0],data[1],data[2]))
label1.pack()
label1.place(x=790,y=577)
btn = Button(app, text="Abrir Imagen", command=select_image)
btn.pack(side="bottom", fill="both", expand="yes", padx="10", pady="10")
btn.place(x=5,y=5)
btn.configure(width=12)
#********************************************
#LABEL H
label2=Label(app,text = 'Filtro HSV')
label2.place(x=0,y=50)
label2.configure(width=7)
label2.configure(height=2)
#LABEL H
label10=Label(app,text = 'Hue')
label10.place(x=0,y=70)
label10.configure(width=7)
label10.configure(height=2)
#SLIDER H MINIMO
Hmin = StringVar()
w1 = Scale(app, from_=0, to=255, orient=HORIZONTAL,variable = Hmin)
w1.pack()
w1.place(x=70,y=70)
w1.configure(width=15)
#SLIDER H MAXIMO
Hmax= StringVar()
w2 = Scale(app, from_=0, to=255, orient=HORIZONTAL,variable = Hmax)
w2.pack()
w2.place(x=190,y=70)
w2.configure(width=15)
#LABEL S
label11=Label(app,text = 'Saturation')
label11.place(x=0,y=120)
label11.configure(width=7)
label11.configure(height=2)
#SLIDER S MINIMO
Smin= StringVar()
w3 = Scale(app, from_=0, to=255, orient=HORIZONTAL,variable = Smin)
w3.pack()
w3.place(x=70,y=120)
w3.configure(width=15)
#SLIDER S MAXIMO
Smax= StringVar()
w4 = Scale(app, from_=0, to=255, orient=HORIZONTAL, variable = Smax)
w4.pack()
w4.place(x=190,y=120)
w4.configure(width=15)
#LABEL V
label11=Label(app,text = 'Value')
label11.place(x=0,y=170)
label11.configure(width=7)
label11.configure(height=2)
#SLIDER V MINIMO
Vmin = StringVar()
w5 = Scale(app, from_=0, to=255, orient=HORIZONTAL, variable = Vmin)
w5.pack()
w5.place(x=70,y=170)
w5.configure(width=15)
#SLIDER V MAXIMO
Vmax = StringVar()
w6= Scale(app, from_=0, to=255, orient=HORIZONTAL,variable = Vmax)
w6.pack()
w6.place(x=190,y=170)
w6.configure(width=15)
#********************************************
app.mainloop()
图像不进行任何更改您必须为每个
比例分配功能
,并且在移动滑块时将执行该功能
tk.Scale(..., command=function_name)
完整版本仅显示比例中的值
import Tkinter as tk
import tkFileDialog
import cv2
from PIL import Image, ImageTk
import numpy as np
# --- functions ---
def select_image():
path = tkFileDialog.askopenfilename()
if path:
image = cv2.imread(path, 1)
data = image.shape
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lw_range = np.array([0, 0, 0])
up_range = np.array([255, 255, 255])
mask = cv2.inRange(hsv, lw_range, up_range)
res = cv2.bitwise_and(image, image, mask= mask)
image = Image.fromarray(res).resize((570,570), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)
label_img = tk.Label(app, image=image, relief=tk.SOLID)
label_img.image = image
label_img.place(x=790, y=5)
label1 = tk.Label(app, text="Informacion Imagen\nAlto:{}\nAncho:{}\nCanales:{}".format(data[0], data[1], data[2]))
label1.place(x=790, y=577)
def modify_image(name, value):
print(name, value)
# --- main ---
app = tk.Tk()
width = app.winfo_screenwidth()
height = app.winfo_screenheight()
app.geometry('{}x{}'.format(width, height))
app.title("TEST")
btn = tk.Button(app, text="Abrir Imagen", command=select_image, width=12)
btn.place(x=5, y=5)
#********************************************
#LABEL H
label2 = tk.Label(app, text='Filtro HSV', width=7, height=2)
label2.place(x=0, y=50)
#LABEL H
label10 = tk.Label(app, text='Hue', width=7, height=2)
label10.place(x=0, y=70)
#SLIDER H MINIMO
Hmin = tk.StringVar()
w1 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL, variable=Hmin, width=15, command=lambda value:modify_image('h_min', value))
w1.place(x=70, y=70)
#SLIDER H MAXIMO
Hmax= tk.StringVar()
w2 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL, variable=Hmax, width=15, command=lambda value:modify_image('h_max', value))
w2.place(x=190, y=70)
#LABEL S
label11 = tk.Label(app, text='Saturation', width=7, height=2)
label11.place(x=0, y=120)
#SLIDER S MINIMO
Smin = tk.StringVar()
w3 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL, variable=Smin, width=15, command=lambda value:modify_image('s_min', value))
w3.place(x=70, y=120)
#SLIDER S MAXIMO
Smax = tk.StringVar()
w4 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL, variable=Smax, width=15, command=lambda value:modify_image('s_max', value))
w4.place(x=190, y=120)
#LABEL V
label11 = tk.Label(app, text='Value', width=7, height=2)
label11.place(x=0, y=170)
#SLIDER V MINIMO
Vmin = tk.StringVar()
w5 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL, variable=Vmin, width=15, command=lambda value:modify_image('v_min', value))
w5.place(x=70, y=170)
#SLIDER V MAXIMO
Vmax = tk.StringVar()
w6 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL,variable=Vmax, width=15, command=lambda value:modify_image('v_max', value))
w6.place(x=190, y=170)
#********************************************
app.mainloop()
您必须为每个比例分配函数,并在移动滑块时执行该函数
tk.Scale(..., command=function_name)
完整版本仅显示比例中的值
import Tkinter as tk
import tkFileDialog
import cv2
from PIL import Image, ImageTk
import numpy as np
# --- functions ---
def select_image():
path = tkFileDialog.askopenfilename()
if path:
image = cv2.imread(path, 1)
data = image.shape
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lw_range = np.array([0, 0, 0])
up_range = np.array([255, 255, 255])
mask = cv2.inRange(hsv, lw_range, up_range)
res = cv2.bitwise_and(image, image, mask= mask)
image = Image.fromarray(res).resize((570,570), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)
label_img = tk.Label(app, image=image, relief=tk.SOLID)
label_img.image = image
label_img.place(x=790, y=5)
label1 = tk.Label(app, text="Informacion Imagen\nAlto:{}\nAncho:{}\nCanales:{}".format(data[0], data[1], data[2]))
label1.place(x=790, y=577)
def modify_image(name, value):
print(name, value)
# --- main ---
app = tk.Tk()
width = app.winfo_screenwidth()
height = app.winfo_screenheight()
app.geometry('{}x{}'.format(width, height))
app.title("TEST")
btn = tk.Button(app, text="Abrir Imagen", command=select_image, width=12)
btn.place(x=5, y=5)
#********************************************
#LABEL H
label2 = tk.Label(app, text='Filtro HSV', width=7, height=2)
label2.place(x=0, y=50)
#LABEL H
label10 = tk.Label(app, text='Hue', width=7, height=2)
label10.place(x=0, y=70)
#SLIDER H MINIMO
Hmin = tk.StringVar()
w1 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL, variable=Hmin, width=15, command=lambda value:modify_image('h_min', value))
w1.place(x=70, y=70)
#SLIDER H MAXIMO
Hmax= tk.StringVar()
w2 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL, variable=Hmax, width=15, command=lambda value:modify_image('h_max', value))
w2.place(x=190, y=70)
#LABEL S
label11 = tk.Label(app, text='Saturation', width=7, height=2)
label11.place(x=0, y=120)
#SLIDER S MINIMO
Smin = tk.StringVar()
w3 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL, variable=Smin, width=15, command=lambda value:modify_image('s_min', value))
w3.place(x=70, y=120)
#SLIDER S MAXIMO
Smax = tk.StringVar()
w4 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL, variable=Smax, width=15, command=lambda value:modify_image('s_max', value))
w4.place(x=190, y=120)
#LABEL V
label11 = tk.Label(app, text='Value', width=7, height=2)
label11.place(x=0, y=170)
#SLIDER V MINIMO
Vmin = tk.StringVar()
w5 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL, variable=Vmin, width=15, command=lambda value:modify_image('v_min', value))
w5.place(x=70, y=170)
#SLIDER V MAXIMO
Vmax = tk.StringVar()
w6 = tk.Scale(app, from_=0, to=255, orient=tk.HORIZONTAL,variable=Vmax, width=15, command=lambda value:modify_image('v_max', value))
w6.place(x=190, y=170)
#********************************************
app.mainloop()
好的:D
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Interfaz para procesar Imagenes
import Tkinter as tk
from PIL import Image
from PIL import ImageTk
import tkFileDialog
import time
import cv2
import numpy as np
from subprocess import check_output
from pyscreenshot import grab
from threading import Thread, Lock
once = True
img_screenshot = None
class App:
original_image = None
hsv_image = None
# switch to make sure screenshot not taken while already pressed
taking_screenshot = False
def __init__(self, master):
self.img_path = None
frame = tk.Frame(master)
frame.grid()
root.title("Cultivos")
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.geometry('{}x{}'.format(width,height))
#self.hue_lbl = tk.Label(text="Hue", fg='red')
#self.hue_lbl.grid(row=2)
self.low_hue = tk.Scale(master, label='Low',from_=0, to=179, length=200,showvalue=2,orient=tk.HORIZONTAL, command=self.show_changes)
self.low_hue.place(x=0, y=50)
self.high_hue = tk.Scale(master,label='High', from_=0, to=179, length=200,orient=tk.HORIZONTAL, command=self.show_changes)
self.high_hue.place(x=200, y=50)
self.high_hue.set(179)
###########################################################################################################
#self.sat_lbl = tk.Label(text="Saturation", fg='green')
#self.sat_lbl.grid(row=5)
self.low_sat = tk.Scale(master, label='Low',from_=0, to=255, length=200,orient=tk.HORIZONTAL, command=self.show_changes)
self.low_sat.place(x=0,y=120)
self.high_sat = tk.Scale(master, label="High", from_=0, to=255, length=200,orient=tk.HORIZONTAL, command=self.show_changes)
self.high_sat.place(x=200,y=120)
self.high_sat.set(255)
###########################################################################################################
#self.val_lbl = tk.Label(text="Value", fg='Blue')
#self.val_lbl.grid(row=8)
self.low_val = tk.Scale(master, label="Low",from_=0, to=255, length=200,orient=tk.HORIZONTAL, command=self.show_changes)
self.low_val.place(x=0,y=190)
self.high_val = tk.Scale(master, label="High",from_=0, to=255, length=200,orient=tk.HORIZONTAL, command=self.show_changes)
self.high_val.place(x=200,y=190)
self.high_val.set(255)
#self.high_val.grid(row=10)
###########################################################################################################
# buttons
#self.print_btn = tk.Button(text='Print', command=self.print_values)
#self.print_btn.place(x=0,y=250)
# Open
self.open_btn = tk.Button(text="Open", command=self.open_file)
self.open_btn.place(x=0,y=10)
#self.open_btn.grid(row=6, column=1)
###########################################################################################################
# timer label
#self.screenshot_timer_lbl = tk.Label(text="Timer", fg='Red')
#self.screenshot_timer_lbl.grid(row=8, column=1)
########################################################################################################## Images
# images
self.hsv_img_lbl = tk.Label(text="HSV", image=None)
self.hsv_img_lbl.place(x=790,y=380)
#self.hsv_img_lbl.grid(row=0, column=0)
self.original_img_lbl = tk.Label(text='Original',image=None)
self.original_img_lbl.place(x=790,y=0)
#self.original_img_lbl.grid(row=0, column=1)
##########################################################################################################
def open_file(self):
global once
once = True
img_file = tkFileDialog.askopenfilename() # Buscar Archivo
# this makes sure you select a file
# otherwise program crashes if not
if img_file != '': # Si La imagen existe
self.img_path = img_file
# Esto solo se asegura de que la imagen se muestra despues de abrirlo
self.low_hue.set(self.low_hue.get()+1)
self.low_hue.set(self.low_hue.get()-1)
else:
print('No se Selecciono Nada')
return 0
def show_changes(self, *args):
global once, img_screenshot
if self.img_path == None: # Si la imagen no hace nada
return 0
# obtener valores de los sliders
# Bajos
low_hue = self.low_hue.get()
low_sat = self.low_sat.get()
low_val = self.low_val.get()
# Altos
high_hue = self.high_hue.get()
high_sat = self.high_sat.get()
high_val = self.high_val.get()
# No hace nada si los valores bajos van mas altos que los valores altos
if low_val > high_val or low_sat > high_sat or low_hue > high_hue:
return 0
# Establece la imagen original una vez, manipula la copia en las siguientes iteraciones
if once:
# Obtiene la imagen del archivo
if self.img_path != 'screenshot':
#img_path = 'objects.png'
# carga BGR
self.original_image = cv2.imread(self.img_path,1)
# image resized
self.original_image = self.resize_image(self.original_image)
self.hsv_image = self.original_image.copy()
#convierte imagen a HSV
self.hsv_image = cv2.cvtColor(self.hsv_image, cv2.COLOR_BGR2HSV)
# gets screenshot
else:
self.original_image = img_screenshot
self.hsv_image = img_screenshot.copy()
#converts image to HSV
self.hsv_image = cv2.cvtColor(self.hsv_image, cv2.COLOR_BGR2HSV)
# OpenCV representa imagenes en orden BGR;
#Sin embargo PIL representa imagenes en orden RGB, por lo que tenemos que intercambiar los canales
self.original_image = cv2.cvtColor(self.original_image, cv2.COLOR_BGR2RGB)
# convierte imagen a formato PIL
self.original_image = Image.fromarray(self.original_image)#.resize((500,500), Image.ANTIALIAS)
# convierta a formato ImageTk
self.original_image = ImageTk.PhotoImage(self.original_image)
# Actualizar la etiqueta de la imagen original
self.original_img_lbl.configure(image=self.original_image)
# Keeping a reference! b/ need to!
#Mantener una referencia! B / necesidad de!
self.original_img_lbl.image = self.original_image
once = False
# Define los valores inferior y superior de la mascara
# define range of colors in HSV (hue up to 179, sat-255, value-255
lower_color = np.array([low_hue,low_sat,low_val])
upper_color= np.array([high_hue,high_sat,high_val])
# red - 0,255,255 (low (hue-10,100,100) high(hue+10,255,255)
# green 60,255,255
# blue -120,255,255
#crea una mascara con el resultado
mask = cv2.inRange(self.hsv_image, lower_color, upper_color)
#res = cv2.bitwise_and(self.original_image.copy(), self.original_image.copy(), mask=mask)
# convierte a formato RGB
#maskbgr = cv2.cvtColor(mask, cv2.COLOR_HSV2BGR)
#maskrgb = cv2.cvtColor(maskbgr, cv2.COLOR_BGR2RGB)
# convierte a formato PIL
mask = Image.fromarray(mask)
# convierte a formato ImageTk
mask = ImageTk.PhotoImage(mask)
# Ajuste de la imagen de hsv a tk etiqueta de imagen
self.hsv_img_lbl.configure(image=mask)
# adding a reference to the image to Prevent python's garbage collection from deleting it
#Anadiendo una referencia a la imagen para evitar que python garbage collection lo elimine
self.hsv_img_lbl.image = mask
def resize_image(self,img,*args):
# Desembala anchura, altura
height, width,_ = img.shape
print("Original size: {} {}".format(width, height))
count_times_resized = 0
while width > 500 or height > 500:
#if width > 300 or height > 300:
# divides images WxH by half
width = width / 2
height = height /2
count_times_resized += 1
# prints x times resized to console
if count_times_resized != 0:
print("Resized {}x smaller, to: {} {}".format(count_times_resized*2,width, height))
# makes sures image is not TOO small
if width < 300 and height < 300:
width = width * 2
height = height * 2
img = cv2.resize(img,(width,height))
return img
# Instance of Tkinter
root = tk.Tk()
# New tkinter instnace of app
app = App(root)
# loops over to keep window active
root.mainloop()
#/usr/bin/python
#-*-编码:utf-8-*-
#Interfaz para procesar成像仪
将Tkinter作为tk导入
从PIL导入图像
从PIL导入ImageTk
导入tkFileDialog
导入时间
进口cv2
将numpy作为np导入
从子流程导入检查输出
从pyscreenshot导入抓取
从线程导入线程,锁定
一次=真
img_屏幕截图=无
类应用程序:
原始图像=无
hsv_图像=无
#切换以确保已按下时未拍摄屏幕截图
截图=错误
定义初始(自我,主):
self.img_路径=无
帧=传统帧(主帧)
frame.grid()
根标题(“Cultivos”)
width=root.winfo_screenwidth()
高度=root.winfo_屏幕高度()
几何体(“{}x{}.”格式(宽度、高度))
#self.hue\u lbl=tk.Label(text=“hue”,fg='red')
#自色调栅格(行=2)
self.low\u色调=tk.Scale(主控,标签='low',从0到179,长度=200,显示值=2,方向=tk.HORIZONTAL,命令=self.show\u更改)
自低色调位置(x=0,y=50)
self.high\u色调=tk.Scale(主控,标签='high',从0到179,长度=200,方向=tk.HORIZONTAL,命令=self.show\u更改)
自高色调位置(x=200,y=50)
自选高色调套装(179)
###########################################################################################################
#self.sat\u lbl=tk.Label(text=“Saturation”,fg='green')
#自卫星栅格(行=5)
self.low\u sat=tk.Scale(master,label='low',from=0,to=255,length=200,orient=tk.HORIZONTAL,command=self.show\u更改)
自低位(x=0,y=120)
self.high\u sat=tk.Scale(master,label=“high”,从0到255,长度=200,方向=tk.HORIZONTAL,命令=self.show\u更改)
自高位(x=200,y=120)
自高_sat.set(255)
###########################################################################################################
#self.val\u lbl=tk.Label(text=“Value”,fg='Blue')
#自值栅格(行=8)
self.low\u val=tk.Scale(master,label=“low”,从0到255,长度=200,方向=tk.HORIZONTAL,命令=self.show\u更改)
自低值位置(x=0,y=190)
self.high\u val=tk.Scale(master,label=“high”,从0到255,长度=200,方向=tk.HORIZONTAL,命令=self.show\u更改)
自高值位置(x=200,y=190)
自高值集(255)
#自高值网格(行=10)
###########################################################################################################
#钮扣
#self.print\u btn=tk.Button(text='print',command=self.print\u值)
#自打印位置(x=0,y=250)
#打开
self.open\u btn=tk.Button(text=“open”,command=self.open\u文件)
自开位置(x=0,y=10)
#自开网格(行=6,列=1)
###########################################################################################################
#计时器标签
#self.screenshot\u timer\u lbl=tk.Label(text=“timer”,fg='Red')
#self.screenshot\u timer\u lbl.grid(行=8,列=1)
##########################################################################################################图像
#图像
self.hsv\u img\u lbl=tk.Label(text=“hsv”,image=None)
自身hsv img lbl位置(x=790,y=380)
#self.hsv\u img\u lbl.grid(行=0,列=0)
self.original\u img\u lbl=tk.Label(text='original',image=None)
自身原始位置(x=790,y=0)
#self.original\u img\u lbl.grid(行=0,列=1)
##########################################################################################################
def open_文件(自身):
全球一次
一次=真
img#u file=tkFileDialog.askopenfilename()#总线车档案
#这确保您选择了一个文件
#否则,程序会崩溃
如果img_文件!='':#Si La imagen existe
self.img\u路径=img\u文件
#他独自一人在阿布里罗的博物馆里拍摄照片
self.low\u hue.set(self.low\u hue.get()+1)
self.low\u hue.set(self.low\u hue.get()-1)
其他:
打印('No se Selecciono Nada')
返回0
def显示_更改(自身,*参数):
全球一次,img_截图
如果self.img_path==None:#Si la imagen no hace nada
返回0
#奥本纳瓦洛雷斯酒店
#巴乔斯
low\u hue=self.low\u hue.get()
low_sat=self.low_sat.get()
low_val=self.low_val.get()
#阿尔托斯
high\u hue=self.high\u hue.get()
high_sat=self.high_sat.get()
high\u val=self.high\u val.get()
#在瓦洛雷斯,没有一个地方是在瓦洛雷斯
如果低色差>高色差或低色差>高色差或低色差>高色差:
返回0
#原版图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋,图片屋
如果有一次:
#阿奇沃酒店
如果self.img_路径!='截图':
#img_path='objects.png'
#卡加BGR
self.original\u image=cv2.imread(self.img\u路径,1)
#图像大小调整
self.original_image=self.resize_image(self