python 取得指定图像或视频鼠标位置的颜色特征

import cv2
#取得指定图像或视频鼠标位置的颜色特征
from pylab import *
from PIL import Image
import sys
import copy
user_input = int(input("如果标视频,请输入1 ;如果标图片,请输入2: "))
if user_input==1:
    input_img = input("请输入视频路径:")
else:
    input_img = input("请输入图像路径:")
#例如E:\demo\1.jpg

def rgb2hex(rgb_list):
    #rgb_list = bgr_list[::-1]
    #print(rgb_list)
    res = "#"
    for a in rgb_list:
        a_hex = hex(a)
        if a<16:
            res+="0"
            res+= a_hex[2:]
        else:
            res+= a_hex[2:]
    return res
            
        


def video_flag():
    frame = 0
    cap = cv2.VideoCapture(input_img)
    fps = cap.get(cv2.CAP_PROP_FPS)
    print("fps: ", fps)
    # frame=cv2.imread('E:/temp/vlcsnap-2020-09-11-17h35m32s537.png')

    def on_EVENT_LBUTTONDOWN(event, x, y, flags, param):
        if event == cv2.EVENT_LBUTTONDOWN:
            xy = "%d,%d" % (x, y)
            cv2.circle(frame, (x-1, y-1), 1, (255, 0, 0), thickness = -1)
            cv2.putText(frame, xy, (x+10, y+10), cv2.FONT_HERSHEY_PLAIN,
                        3.0, (0,0,0), thickness = 3)
            print("x:{},y:{}".format(x,y))
            bgr_list = frame[y, x]
            rgb_list = bgr_list[::-1]
            print("RGB为: ", rgb_list)
            print("十六进制颜色:", rgb2hex(rgb_list))
            print("--"*20)
            cv2.imshow("video", frame)
    cv2.namedWindow('video', cv2.WINDOW_NORMAL)
    cv2.setMouseCallback("video", on_EVENT_LBUTTONDOWN)

    while(True):
        ret, frame = cap.read()
        cv2.imshow("video", frame)
        c = cv2.waitKey(1)
        if c == 27:
            break
    cap.release()
    cv2.destroyAllWindows()

def image_flag():
    frame = 0
    frame=cv2.imread(input_img)
    

    def on_EVENT_LBUTTONDOWN(event,x,y,flags,param):
        if event == cv2.EVENT_LBUTTONDOWN:
            xy = "%d,%d" % (x, y)
            cv2.circle(frame, (x-1, y-1), 1, (255, 155, 0), thickness = -1)
            cv2.putText(frame, xy, (x, y), cv2.FONT_HERSHEY_PLAIN,
                        3.0, (0,0,0), thickness = 3)
            print("x:{},y:{}".format(x,y))
            bgr_list = frame[y, x]
            rgb_list = bgr_list[::-1]
            print("RGB为: ", rgb_list)
            print("十六进制颜色:", rgb2hex(rgb_list))
            print("--"*20)
            cv2.imshow("video", frame)
    cv2.namedWindow('video', cv2.WINDOW_NORMAL)
    cv2.setMouseCallback("video", on_EVENT_LBUTTONDOWN)


    while(True):
        cv2.imshow("video", frame)
        c = cv2.waitKey(1)
        if c == 27:
            break
    cv2.destroyAllWindows()

if int(user_input) == 1:
    video_flag()
elif int(user_input) == 2:
    image_flag()
else:
    print("输入错误!请输入1或者2!")

 

posted @ 2023-03-23 10:07  myrj  阅读(112)  评论(0编辑  收藏  举报