[Tool] python RGB and HSV slider threshold segmentation tool

renderings

 

Operation interface diagram:

Introduction to use:

Press n to read the next picture

Press p to start/stop video

Keep last threshold parameters

Integration code:

import os
from tkinter import *
from tkinter.filedialog import askopenfilename ,askdirectory
import cv2
import numpy as np
import queue
from threading import Thread

class ImageTool():
    def __init__(self):
        self.vid=None
        self.tmp_q=queue.Queue(500)
        self.tmp_list=None
        self.config='./imagetool.txt'
        self.info={}
        self.url=""
        self.method="hsv"


    def pull(self):
        fps=1
        while True:
            ret,frame=self.vid.read()
            if self.tmp_q.qsize()<10:
                self.tmp_q.put(frame)


    def getframe(self):
        print("读取图片")
        #摄像头拉流
        if self.url.startswith('rtsp'):
            if self.vid is None:
                print("读取摄像机视频流")
                self.vid=cv2.VideoCapture(self.url)
                q=Thread(target=self.pull)
                q.start()

            while True:
                if self.tmp_q.qsize()>0:
                    return self.tmp_q.get()

        #文件夹读取
        elif os.path.isdir(self.url):
            if self.tmp_list is None:
                print("读取文件夹")
                self.tmp_list =os.listdir(self.url)
                for i in self.tmp_list:
                    if self.tmp_q.qsize()<500:
                        self.tmp_q.put(os.path.join(self.url,i))

            imgpath=self.tmp_q.get()
            self.tmp_q.put(imgpath)
            return cv2.imread(imgpath)

        #视频文件
        elif self.url.split('.')[-1] in ['avi','mp4']:
            if self.vid is None:
                print("读取视频文件")
                self.vid=cv2.VideoCapture(self.url)

            ret,frame=self.vid.read()
            return frame

        #单张图片
        elif self.url.split('.')[-1] in ['jpg','jpeg','png','bmp']:
            print("读取图片")
            return cv2.imread(self.url)
        else:
            print("url 出现错我")


    def imageshow(self,cs,image):
        c1, c2, c3, c4, c5, c6=cs[:]
        img = cv2.resize(image, (960, 640))

        mask=None
        lower = np.array([c1, c3, c5])
        upper = np.array([c2, c4, c6])

        if self.method=="hsv":
            imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            mask = cv2.inRange(imgHSV, lower, upper)
        elif self.method=="bgr":
            mask = cv2.inRange(img, lower, upper)
        elif self.method=="g0hsv":
            img[:,:,1]=0
            imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            mask = cv2.inRange(imgHSV, lower, upper)


        cv2.imshow("original", img)
        cv2.imshow("Mask", mask)


    def start(self):
        names=[['H','S','V'],['B','G','R'],[]]
        ind=0

        init_=['0']*6
        if  os.path.exists(self.config):
            with open(self.config,'r') as r:
                oneline=r.read()
                init_=oneline.split(',')[:6]
                r.close()
        init_=[int(i) for i in init_]

        def empty(a):
            pass
        cv2.namedWindow("TrackBars")
        cv2.resizeWindow("TrackBars",720,350)
        cv2.createTrackbar(f"{names[ind][0]} min", "TrackBars", init_[0], 255, empty)
        cv2.createTrackbar(f"{names[ind][0]} max", "TrackBars", init_[1], 255, empty)
        cv2.createTrackbar(f"{names[ind][1]} min", "TrackBars", init_[2], 255, empty)
        cv2.createTrackbar(f"{names[ind][1]} max", "TrackBars", init_[3], 255, empty)
        cv2.createTrackbar(f"{names[ind][2]} min", "TrackBars", init_[4], 255, empty)
        cv2.createTrackbar(f"{names[ind][2]} max", "TrackBars", init_[5], 255, empty)


        print("开始读图")
        image=self.getframe()
        print(image.shape)
        stop=0
        while True:
            if stop ==1:
                image=self.getframe()

            # 根据字符取数据值
            c1 = cv2.getTrackbarPos(f"{names[ind][0]} min", "TrackBars")
            c2 = cv2.getTrackbarPos(f"{names[ind][0]} max", "TrackBars")
            c3 = cv2.getTrackbarPos(f"{names[ind][1]} min", "TrackBars")
            c4 = cv2.getTrackbarPos(f"{names[ind][1]} max", "TrackBars")
            c5 = cv2.getTrackbarPos(f"{names[ind][2]} min", "TrackBars")
            c6 = cv2.getTrackbarPos(f"{names[ind][2]} max", "TrackBars")
            with open(self.config,'w') as w:
                w.write(f'{c1},{c2},{c3},{c4},{c5},{c6}')
                w.close()

            self.imageshow([c1,c2,c3,c4,c5,c6],image)


            k = cv2.waitKey(1)
            if k == ord('q'):
                break
            elif k== ord('p'):
                stop=1-stop
            elif k== ord('n'):
                image=self.getframe()

        cv2.destroyAllWindows()

if __name__ == '__main__':
    tool=ImageTool()
    methods=['hsv','bgr','g0hsv']
    tool.method=methods[2]

    tool.url="C:/Users/Shanmh/Desktop/撕裂/63撕裂有夹角记录.mp4"
    tool.url="C:/Users/Shanmh/Desktop/0425/downimages"

    # tool.url="rtsp://@192.168.200.63:554/h264/ch1/main/av_stream"


    tool.start()

 Note:

This code is only for personal collection. If there is any infringement, it will be deleted after contacting us.

Guess you like

Origin blog.csdn.net/qq_55542491/article/details/130319253