import SimpleITK as sitk
import os
import cv2
import pydicom
import numpy as np
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
import configparser
import sys

class MyApp(object):
    def __init__(self, parent):
        self.rootframe = tk.Frame(parent)
        self.rootframe.pack()
        self.setupUI()
        self.config()
    def setupUI(self):
        self.button_browse = ttk.Button(root, text='...', width=3, command=self.SlectSourceFloder)
        self.button_browse.place(x=200, y=8)

        self.button_dest = ttk.Button(root, text='...', width=3, command=self.SlectDestFloder)
        self.button_dest.place(x=200, y=48)

        self.button_convert = ttk.Button(root, text='转换', width=20, command=self.convertVideoButton)
        self.button_convert.place(x=40, y=130)

        self.scale = tk.Scale(root, from_=0, to=10, orient=tk.HORIZONTAL, label='')
        self.scale.set(3)
        self.scale.place(x=80, y=75)

        self.text_sources = tk.Text(root, width=18, height=1, font=('tahoma', 9), bd=2)
        self.text_sources.place(x=70, y=10)
        self.label_sources = tk.Label(root, text='来源目录', font=('tahoma', 10))
        self.label_sources.place(x=10, y=10)
        self.text_dest = tk.Text(root, width=18, height=1, font=('tahoma', 9), bd=2)
        self.text_dest.place(x=70, y=50)
        self.label_dest = tk.Label(root, text='目标目录', font=('tahoma', 10))
        self.label_dest.place(x=10, y=50)

        self.check_CLAHE = tk.IntVar()
        self.RB_origin = tk.Checkbutton(root, text='CLAHE', variabl=self.check_CLAHE, command='')
        self.RB_origin.place(x=10, y=90)
        self.RB_origin.select()
      # 均衡
        self.check_equalizeHist = tk.IntVar()
        self.equalizeHist_check = tk.Checkbutton(root, text='均衡', variabl=self.check_equalizeHist, command='')
        self.equalizeHist_check.place(x=180, y=90)
        self.equalizeHist_check.select()

    def get_cf(self,key):
        cf = configparser.ConfigParser()
        cur_path = os.path.dirname(os.path.realpath(__file__))
        config_path = os.path.join(cur_path, "dicom.conf")
        # print(config_path)
        cf.read(config_path)
        value = cf.get("dicom", key)
        return value

    def set_cf(self,key, value):
        cf = configparser.ConfigParser()
        cur_path = os.path.dirname(os.path.realpath(__file__))
        config_path = os.path.join(cur_path, "dicom.conf")
        cf.read(config_path)
        cf.set('dicom', key, value)
        with open(config_path, "w+") as f:
            cf.write(f)

    def loadFile(self,filename):
        ds = sitk.ReadImage(filename)
        img_array = sitk.GetArrayFromImage(ds)
        frame_num, width, height = img_array.shape
        return img_array, frame_num, width, height

    def loadFileInformation(self,filename):
        self.information = {}
        ds = pydicom.read_file(filename)
        self.information['PatientID'] = ds.PatientID
        self.information['PatientName'] = ds.PatientName
        # self.information['PatientBirthDate'] = ds.PatientBirthDate
        self.information['PatientSex'] = ds.PatientSex
        self.information['StudyID'] = ds.StudyID
        self.information['StudyDate'] = ds.StudyDate
        self.information['StudyTime'] = ds.StudyTime
        self.information['InstitutionName'] = ds.InstitutionName
        self.information['Manufacturer'] = ds.Manufacturer

        self.information['InstanceNumber'] = ds.InstanceNumber
        angle1 = ds.PositionerPrimaryAngle
        if angle1 >= 0:
            self.information['PositionerPrimaryAngle'] = 'LAO ' + str(abs(angle1))
        else:
            self.information['PositionerPrimaryAngle'] = 'RAO ' + str(abs(angle1))
        # self.information['PositionerPrimaryAngle']=ds.PositionerPrimaryAngle
        angle2 = ds.PositionerSecondaryAngle
        if angle2 >= 0:
            self.information['PositionerSecondaryAngle'] = 'CRA ' + str(abs(angle2))
        else:
            self.information['PositionerSecondaryAngle'] = 'CAU ' + str(abs(angle2))

        try:
            self.information['NumberOfFrames'] = ds.NumberOfFrames
            self.information['RecommendedDisplayFrameRate'] = ds.RecommendedDisplayFrameRate
        except:
            pass
        self.information['ImageType'] = ds.ImageType
        #return self.self.information

    def autoEqualize(self,img_array_a):
        img_array_list = []
        for img in img_array_a:
            img_array_list.append(cv2.equalizeHist(img))
        img_array_equalized = np.array(img_array_list)
        return img_array_equalized

    def writeVideo(self,img_array, directory):
        frame_num, width, height = img_array.shape
        if self.information['ImageType'].__contains__('SECONDARY'):  # 如果是静态图片
            for img in img_array:
                cv2.imwrite(self.get_jpgname(), img)
            return
        filename_output = self.get_filename(directory)
        fourcc = cv2.VideoWriter_fourcc(*'MJPG')
        video = cv2.VideoWriter(filename_output, fourcc, 15, (width, height))
        for img in img_array:
            img_rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
            video.write(img_rgb)  # Write video file frame by frame
        video.release()

    def convertVideoButton(self):
        filepath = self.source_dir
        pathDir = os.listdir(filepath)
        for allDir in pathDir:

            filename = os.path.join('%s/%s' % (filepath, allDir))
            # try:
            self.loadFileInformation(filename)
            dirs = self.get_dir()
            #self.loadFileButton(filename)
            img_array, frame_num, width, height = self.loadFile(filename)
            img_arrays = self.core(img_array)
            self.writeVideo(img_arrays, dirs)
            # except e:
            #     print(e)

        messagebox.showinfo('提示', '完事了')

    def core(self,img_array_c):
        if self.check_equalizeHist.get():
            #print("均衡")
            img_array_c = self.autoEqualize(img_array_c)
        if self.check_CLAHE.get():
            img_array_c = self.limitedEqualize(img_array_c)
        return img_array_c

    def limitedEqualize(self,img_array):
        img_array_list = []
        for img in img_array:
            clahe = cv2.createCLAHE(clipLimit=self.scale.get(),
                                    tileGridSize=(8, 8))  # CLAHE (Contrast Limited Adaptive Histogram Equalization)
            img_array_list.append(clahe.apply(img))

        img_array_limited_equalized = np.array(img_array_list)
        return img_array_limited_equalized

    def config(self):
        cur_path = os.path.dirname(os.path.realpath(__file__))
        config_path = os.path.join(cur_path, "dicom.conf")
        if os.path.exists(config_path):
            self.source_dir = self.get_cf('source_dir')
            self.dest_dir = self.get_cf('dest_dir')
        else:
            config =configparser.ConfigParser()
            config['dicom'] = {'dest_dir': sys.path[0], 'source_dir': sys.path[0]}

            with open(config_path, 'w') as configfile:
                config.write(configfile)
            self.source_dir =  self.get_cf('source_dir')
            self.dest_dir =  self.get_cf('dest_dir')
        self.text_dest.delete('1.0', tk.END)
        self.text_dest.insert('1.0', self.dest_dir)
        self.text_sources.delete('1.0', tk.END)
        self.text_sources.insert('1.0', self.source_dir)

    def SlectSourceFloder(self):

        directory = filedialog.askdirectory(initialdir=self.source_dir)
        if directory == '':
            return
        self.source_dir = directory
        self.set_cf("source_dir", self.source_dir)
        self.text_sources.delete('1.0', tk.END)
        self.text_sources.insert('1.0', self.source_dir)

    def SlectDestFloder(self):

        directory = filedialog.askdirectory(initialdir=self.dest_dir)
        if directory == '':
            return
        self.dest_dir = directory
        self.set_cf("dest_dir", self.dest_dir)
        self.text_dest.delete('1.0', tk.END)
        self.text_dest.insert('1.0', self.dest_dir)

    def check(self):
        if self.check_CLAHE.get():
            scale['state'] = 'normal'
        else:
            scale['state'] = 'disable'

    def get_origin(self):
        str = ''
        if self.check_CLAHE.get():
            str = str + '_CLAHE'
        if self.check_equalizeHist.get():
            str = str + '_HIST'
        return str

    def get_dir(self):
        dirs = self.dest_dir + "/" + str(self.information['PatientName']).replace('^', '').replace(' ', '_') + '_' + \
               self.information['StudyDate']  # 目标文件为姓名+手术日期
        if not os.path.exists(dirs):  # 判断目标文件夹是否存在
            os.makedirs(dirs)
        return dirs

    def get_filename(self,directory):
        if self.information['ImageType'].__contains__('SECONDARY'):
            filename_output = directory + '/0' + str(self.information['InstanceNumber']) + self.get_origin() + '.avi'
        else:
            filename_output = directory + '/' + str(self.information['InstanceNumber']) + self.get_origin() + '.avi'
        return filename_output

    def add_text(self,imgs):
        imgs = cv2.putText(imgs, str(self.information['StudyDate']), (10, 20), cv2.FONT_HERSHEY_COMPLEX, 0.5,
                           (255, 255, 255), 2)  # 视频添加文字
        imgs = cv2.putText(imgs, str(self.information['PositionerPrimaryAngle']), (10, 50), cv2.FONT_HERSHEY_COMPLEX, 0.5,
                           (255, 255, 255), 2)
        imgs = cv2.putText(imgs, str(self.information['PositionerSecondaryAngle']), (10, 80), cv2.FONT_HERSHEY_COMPLEX, 0.5,
                           (255, 255, 255), 2)
        return imgs

    def creat_clahe(self,imgs, limit):  # 优化对比第一道工序
        clahe = cv2.createCLAHE(clipLimit=limit,
                                tileGridSize=(8, 8))  # CLAHE (Contrast Limited Adaptive Histogram Equalization)
        imgs = clahe.apply(imgs)
        return imgs

    def get_jpgname(self):
        jpg = self.get_dir() + '/' + str(self.information['InstanceNumber']) + self.get_origin() + '.jpg'
        return jpg

if __name__ == '__main__':
  root = tk.Tk()
  w = 250
  h = 180
  ws = root.winfo_screenwidth()
  hs = root.winfo_screenheight()
  x = (ws / 2) - (w / 2)
  y = (hs / 2) - (h / 2)
  root.geometry('%dx%d+%d+%d' % (w, h, x, y))
  root.title('DICOM TO AVI')
  MyApp(root) # 注意这句
  root.mainloop()


class Session:
    def findPlayer(pname):
        f = open("players.txt", "r")
        while True:
            pline = f.readline()
            if pline != "":
                pn = ""
                i = 0
                while True:
                    c = pline[i]
                    if c != " ":
                        pn += c
                    else:
                        i += 1
                        break
                    i += 1
                if Session.encr(pname) == pn:
                    return pline[i:len(pline)-1]
            else:
                return ""

    def regPlayer(pname, pwd):
        f = open("players.txt", "a")
        f.write(Session.encr(pname) + " " + Session.encr(pwd) + '\n')
        f.close()

    def encr(pwd):
        ref = pwd
        lim = len(pwd)
        for i in range(lim):
            ref = ref[i:] + pwd[i] + ref[:i]

        aord = ord('a')
        zerord = ord('0')
        trans = 0

        res01 = ["",""]
        for i in range(lim):
            trans = (trans + ord(ref[i]))%26
            res01[0] += chr(aord + (trans*(ord(ref[i]))) % 26)
        for i in range(lim, 2*lim):
            trans = (2*trans - ord(ref[i]))%10
            res01[1] += chr(zerord + (trans*(ord(ref[i]))) % 10)

        res = ""
        for i in range(lim):
            s = (i*i + ord(pwd[i])) % 5
            res += res01[s%2][i] + res01[(s+1)%2][i]
        return res


import random

class Creature():

    def __init__(self, name, is_ai):
        self.name = name
        self.hp = random.randint(50, 61)
        self.full_hp = self.hp
        self.is_ai = is_ai
        #怪物类型分为 0: 攻击型, 1: 均衡型, 2: 反击型
        self.monster_type = random.randint(0,3)

    def is_alive(self):
        if self.hp > 0:
            return True
        else:
            return False

    def attack(self):
        attack_value = 20
        if self.monster_type == 0:
            attack_value += random.randint(0,5)
        elif self.monster_type == 1:
            pass
        else:
            attack_value -= random.randint(0,5)
        #AI输出折损60%
        if self.is_ai:
            attack_value = int(attack_value * 0.4)
        else:
            pass
        return attack_value

    def being_attack(self, damage):
        self.hp -= damage

    #反击成功率
    def counter_attack(self):
        if self.monster_type == 0:
            if random.randint(0,100) < 30 + 20 * (self.hp / self.full_hp):
                return True
            else:
                return False
        elif self.monster_type == 1:
            if random.randint(0,100) < 50 + 15 * (self.hp / self.full_hp):
                return True
            else:
                return False
        else:
            if random.randint(0,100) < 70 + 10 * (self.hp / self.full_hp):
                return True
            else:
                return False

    def check_hp_state(self):
        return [self.hp, self.full_hp]

    def get_monster_type(self):
        if self.monster_type == 0:
            return '攻击型'
        elif self.monster_type == 1:
            return '均衡型'
        else:
            return '反击型'

    #不同怪物采取行动的策略
    def is_ai_attack(self):
        if self.monster_type == 0:
            if random.randint(0,100) < 0 + self.full_hp - self.hp:
                return True
            else:
                return False
        elif self.monster_type == 1:
            if random.randint(0,100) < 25 + self.full_hp - self.hp:
                return True
            else:
                return False
        else:
            if random.randint(0,100) < 50 + self.full_hp - self.hp:
                return True
            else:
                return False

player_name = input('请输入您的游戏ID：')
player = Creature(player_name, False)
monster1 = Creature('怪物1', True)
monster2 = Creature('怪物2', True)
print(
'''

    游戏规则：
        怪物类型分为“攻击型”、“均衡型”和“防御型”。
        “攻击型”怪物的基础攻击力高，反击成功率低，AI的主动攻击欲望强；
        “均衡型”怪物的基础攻击力中，反击成功率中，AI的主动攻击欲望中等；
        “反击型”怪物的基础攻击力低，反击成功率高，AI的主动攻击欲望弱。

        行动顺序固定为：您 -> 怪物1 -> 怪物2
        由于是一打二，所以AI的输出会有折损，但是血量和您相当。
        血量越低，反击成功率越高，请合理选择攻击或反击！

        祝您好运！

''')
print('您战宠的怪物类型为"{}"，两个敌人的怪物类型分别为"{}"和"{}"。'.format(player.get_monster_type(),
    monster1.get_monster_type(), monster2.get_monster_type()))

round = 1
while player.is_alive() and (monster1.is_alive() or monster2.is_alive()):
    print('\n********第{}回合********'.format(round))
    #预置本轮伤害
    player_damage_this_turn = player.attack()
    monster1_damage_this_turn = monster1.attack()
    monster2_damage_this_turn = monster2.attack()
    #预置怪物本轮行动
    is_monster1_attack_this_turn = monster1.is_ai_attack()
    is_monster2_attack_this_turn = monster2.is_ai_attack()
    #获取玩家行动
    while True:
        user_input = input('Attack or counter attack? (A/C):')
        if user_input == 'A':
            print('您选择了进攻')
            break
        elif user_input == 'C':
            print('您选择了反击')
            break
        else:
            pass
    #获取玩家选取的目标
    if user_input == 'A':
        while True:
            try:
                target = int(input('Select target: (1/2)'))
                if target == 1:
                    print('您选择了攻击怪物1')
                    break
                elif target == 2:
                    print('您选择了攻击怪物2')
                    break
                else:
                    continue
            except:
                continue
        if monster1.is_alive():
            print('怪物1选择了{}'.format('进攻' if is_monster1_attack_this_turn else '反击'))
        if monster2.is_alive():
            print('怪物2选择了{}'.format('进攻' if is_monster2_attack_this_turn else '反击'))
        if target == 1:
            if monster1.is_alive():
                #怪物1是否反击
                if not is_monster1_attack_this_turn:
                    #怪物1是否反击成功
                    if monster1.counter_attack():
                        player.being_attack(monster1_damage_this_turn)
                        print('怪物1反击成功！！对您造成{}点反击伤害，您当前的血条：{}/{}'.format(monster1_damage_this_turn,
                            max(player.check_hp_state()[0], 0), player.check_hp_state()[1]))
                    else:
                        monster1.being_attack(player_damage_this_turn)
                        print('您对怪物1造成了{}点伤害，怪物1当前的血条：{}/{}'.format(player_damage_this_turn,
                            max(monster1.check_hp_state()[0], 0), monster1.check_hp_state()[1]))
                else:
                    monster1.being_attack(player_damage_this_turn)
                    print('您对怪物1造成了{}点伤害，怪物1当前的血条：{}/{}'.format(player_damage_this_turn,
                        max(monster1.check_hp_state()[0], 0), monster1.check_hp_state()[1]))
            else:
                print('您鞭尸了怪物1')

        elif target == 2:
            if monster2.is_alive():
                #怪物2是否反击
                if not is_monster2_attack_this_turn:
                    #怪物2是否反击成功
                    if monster2.counter_attack():
                        player.being_attack(monster2_damage_this_turn)
                        print('怪物2反击成功！！对您造成{}点反击伤害，您当前的血条：{}/{}'.format(monster2_damage_this_turn,
                            max(player.check_hp_state()[0], 0), player.check_hp_state()[1]))
                    else:
                        monster2.being_attack(player_damage_this_turn)
                        print('您对怪物2造成了{}点伤害，怪物2当前的血条：{}/{}'.format(player_damage_this_turn,
                            max(monster2.check_hp_state()[0], 0), monster2.check_hp_state()[1]))
                else:
                    monster2.being_attack(player_damage_this_turn)
                    print('您对怪物2造成了{}点伤害，怪物2当前的血条：{}/{}'.format(player_damage_this_turn,
                        max(monster2.check_hp_state()[0], 0), monster2.check_hp_state()[1]))
            else:
                print('您鞭尸了怪物2')
        else:
            print('**********Debug: 玩家目标选取异常***********')

        if monster1.is_alive():
            #怪物1主动攻击
            if is_monster1_attack_this_turn:
                if player.is_alive():
                    player.being_attack(monster1_damage_this_turn)
                    print('怪物1向您发起攻击，对您造成{}点伤害，您当前的血条：{}/{}'.format(monster1_damage_this_turn,
                        max(player.check_hp_state()[0], 0), player.check_hp_state()[1]))
                else:
                    print('怪物1鞭尸了您')
        if monster2.is_alive():
            #怪物2主动攻击
            if is_monster2_attack_this_turn:
                if player.is_alive():
                    player.being_attack(monster2_damage_this_turn)
                    print('怪物2向您发起攻击，对您造成{}点伤害，您当前的血条：{}/{}'.format(monster2_damage_this_turn,
                        max(player.check_hp_state()[0], 0), player.check_hp_state()[1]))
                else:
                    print('怪物2鞭尸了您')

    elif user_input == 'C':
        if monster1.is_alive():
            print('怪物1选择了{}'.format('进攻' if is_monster1_attack_this_turn else '反击'))
        if monster2.is_alive():
            print('怪物2选择了{}'.format('进攻' if is_monster2_attack_this_turn else '反击'))
        if monster1.is_alive():
            #怪物1主动攻击
            if is_monster1_attack_this_turn:
                if player.is_alive():
                    #玩家反击成功
                    if player.counter_attack():
                        monster1.being_attack(player_damage_this_turn)
                        print('您成功反击了怪物1的攻击！！对怪物1造成{}点伤害，怪物1当前的血条：{}/{}'.format(player_damage_this_turn,
                            max(monster1.check_hp_state()[0], 0), monster1.check_hp_state()[1]))
                    #玩家反击失败
                    else:
                        player.being_attack(monster1_damage_this_turn)
                        print('怪物1向您发起攻击，对您造成{}点伤害，您当前的血条：{}/{}'.format(monster1_damage_this_turn,
                            max(player.check_hp_state()[0], 0), player.check_hp_state()[1]))
                else:
                    print('怪物1鞭尸了您')

        if monster2.is_alive():
            #怪物2主动攻击
            if is_monster2_attack_this_turn:
                if player.is_alive():
                    #玩家反击成功
                    if player.counter_attack():
                        monster2.being_attack(player_damage_this_turn)
                        print('您成功反击了怪物2的攻击！！对怪物2造成{}点伤害，怪物2当前的血条：{}/{}'.format(player_damage_this_turn,
                            max(monster2.check_hp_state()[0], 0), monster1.check_hp_state()[1]))
                    #玩家反击失败
                    else:
                        player.being_attack(monster2_damage_this_turn)
                        print('怪物2向您发起攻击，对您造成{}点伤害，您当前的血条：{}/{}'.format(monster2_damage_this_turn,
                            max(player.check_hp_state()[0], 0), player.check_hp_state()[1]))
                else:
                    print('怪物2鞭尸了您')
    else:
        print('*********Debug: 玩家输入行动异常***********')
    print('\n血量情况：  玩家：{}/{}，怪物1：{}/{}，怪物2：{}/{}'.format(
        max(player.check_hp_state()[0], 0), player.check_hp_state()[1],
        max(monster1.check_hp_state()[0], 0), monster1.check_hp_state()[1],
        max(monster2.check_hp_state()[0], 0), monster2.check_hp_state()[1]))
    round += 1

if player.is_alive():
    print('\n\n{}，恭喜您获得了胜利！'.format(player_name))
else:
    print('\n\n{}，很遗憾您失败了！'.format(player_name))


import streamlit as st
import cv2
from PIL import Image
import numpy as np
import os

def load_image(image_file):
	img = Image.open(image_file)
	return img

def main():
    """Train Images"""

    st.title("House Monitoring System")

    html_temp = """

Face Recognition WebApp

    """
    st.markdown(html_temp, unsafe_allow_html=True)

    image_file = st.file_uploader("Upload Image", type=['jpg', 'png', 'jpeg'])

    filename=st.text_input("Enter the name of person")

    if st.button("Upload"):
        if image_file is not None:
            our_image = Image.open(image_file)
            st.text("Original Image")
            st.image(our_image)
            st.image(load_image(image_file),width=250)
            with open(os.path.join("C:\\Users\\asus\\OneDrive\\Desktop\\ie\\Training_images",filename+str(".jpg")),"wb") as f:
                f.write((image_file).getbuffer())
if __name__ == '__main__':
    main()


'''
Linear Approch
--------------
Time - O(n)
Space - O(1)
'''

def isValidSubsequence(array, sequence):
    i = 0
    j = 0

    while i < len(array) and j < len(sequence):
        if sequence[j] == array[i]:
            j += 1
        i += 1

    return j == len(sequence)

array = [5, 1, 22, 25, 6, -1, 8, 10]
sequence = [1, 6, -1, 10]
print(isValidSubsequence(array, sequence))

array = [5, 1, 22, 25, 6, -1, 8, 10]
sequence = [5, 1, 22, 6, -1, 8, 10]
print(isValidSubsequence(array, sequence))

array = [5, 1, 22, 25, 6, -1, 8, 10]
sequence = [5, 1, 22, 10]
print(isValidSubsequence(array, sequence))

array = [5, 1, 22, 25, 6, -1, 8, 10]
sequence = [5, 45, 2, 10]
print(isValidSubsequence(array, sequence))


import numpy as np
import shapely
from shapely.geometry import Polygon,MultiPoint  #多边形

line1=[908,215,934,312,752,355,728,252]   #四边形四个点坐标的一维数组表示，[x,y,x,y....]
a=np.array(line1).reshape(4, 2)   #四边形二维坐标表示
poly1 = Polygon(a).convex_hull  #python四边形对象，会自动计算四个点，最后四个点顺序为：左上 左下  右下 右上 左上
print(Polygon(a).convex_hull)  #可以打印看看是不是这样子

line2=[923,308,758,342,741,262,907,228]
b=np.array(line2).reshape(4, 2)
poly2 = Polygon(b).convex_hull
print(Polygon(b).convex_hull)

union_poly = np.concatenate((a,b))   #合并两个box坐标，变为8*2
#print(union_poly)
print(MultiPoint(union_poly).convex_hull)      #包含两四边形最小的多边形点
if not poly1.intersects(poly2): #如果两四边形不相交
    iou = 0
else:
    try:
        inter_area = poly1.intersection(poly2).area   #相交面积
        print(inter_area)
        #union_area = poly1.area + poly2.area - inter_area
        union_area = MultiPoint(union_poly).convex_hull.area
        print(union_area)
        if union_area == 0:
            iou= 0
        #iou = float(inter_area) / (union_area-inter_area)  #错了
        iou=float(inter_area) / union_area
        # iou=float(inter_area) /(poly1.area+poly2.area-inter_area)
        # 源码中给出了两种IOU计算方式，第一种计算的是: 交集部分/包含两个四边形最小多边形的面积
        # 第二种： 交集 / 并集（常见矩形框IOU计算方式）
    except shapely.geos.TopologicalError:
        print('shapely.geos.TopologicalError occured, iou set to 0')
        iou = 0

print(a)

print(iou)


from django.urls import path,include
from .views import (User,Profile,PostAPIView,
                    UserPosts,Search,FollowerAPIView,
                    FollowingAPIView,FeedAPIView,StartFollowAPIView,
                    StopFollowAPIView,UniqueEmailCheck,UniqueUsernameCheck,
                    Register,
                    UpdatePicAPIView,Profile_Detail)
from django.views.decorators.csrf import csrf_exempt

urlpatterns = [
    path('users/', User.as_view(),name="users"),
    path('rest-auth/',include("rest_auth.urls")),
    path('api-auth/',include("rest_framework.urls")),
    path("profile/<str:usrname>",Profile.as_view(),name="profile-detail"),
    path("create-post",PostAPIView.as_view(),name="postapi"),
    path("post/<int:pk>",PostAPIView.as_view(),name="single-post"),
    path("post/<int:pk>/edit",PostAPIView.as_view(),name="post-edit"),
    path("profile/<str:username>/posts",UserPosts.as_view(),name="user-posts"),
    path("search",Search.as_view(),name="search"),
    path("profile/<str:username>/followers",FollowerAPIView.as_view(),name="followers"),
    path("profile/<str:username>/following",FollowingAPIView.as_view(),name="following"),
    path("gethomefeed",FeedAPIView.as_view(),name="home-feed"),
    path("addfollow/<str:profile_username>",StartFollowAPIView.as_view(),name="start-follow"),
    path("removefollow/<str:profile_username>",StopFollowAPIView.as_view(),name="stop-follow"),
    path("doesemailexist",UniqueEmailCheck,name="check-email"),
    path("doesusernameexist",UniqueUsernameCheck,name="username-check"),
    path("register",Register,name="my-register"),
    # path("testing",csrf_exempt(Image.as_view()),name="dhgtd"),
    path("update-pic",UpdatePicAPIView.as_view(),name="update-pic"),
    path("profile-detail",Profile_Detail,name="profile-detail"),
]


import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
from sklearn.metrics import average_precision_score
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import roc_curve, auc
from my_dataset import DefectDataset, joint_dataset, joint_train_dataset, DefectDataset2
from torch.utils.data import DataLoader
from sklearn.metrics import f1_score
from sklearn.metrics import jaccard_score

def roc(labels, scores, saveto=None):
    """Compute ROC curve and ROC area for each class"""
    roc_auc = dict()
    # True/False Positive Rates.
    fpr, tpr, _ = roc_curve(labels, scores)
    roc_auc = auc(fpr, tpr)
    return roc_auc

# scores_path = ['t2_t1_score.npy', 't2_t1_score_transfer.npy', 't2_t1_score_transfer_en.npy',
#                 't2_t1_score_transfer_all.npy', 't2_t1_score_transfer1_all.npy','t2_t1_score_transfer1au_all.npy']
# labels_path = ['t2_t1_label.npy', 't2_t1_label_transfer.npy', 't2_t1_label_transfer_en.npy',
#                 't2_t1_label_transfer_all.npy','t2_t1_label_transfer1_all.npy','t2_t1_label_transfer1au_all.npy']

# scores_path = ['scores_out_unet_dic.npy', 'scores_out_unet_dic_aug.npy','scores_out_unet_dic_att.npy',
#                 'scores_out_unet_dic_att_tranf.npy']

# labels_path = ['labels_out_unet_dic.npy', 'labels_out_unet_dic_aug.npy','labels_out_unet_dic_att.npy',
#                 'labels_out_unet_dic_att_tranf.npy']

# scores_path = ['t2_t1_score.npy', 't2_t1_score_transfer.npy', 't2_t1_score_transfer_en.npy',
#                 't2_t1_score_transfer_all.npy']
# labels_path = ['t2_t1_label.npy', 't2_t1_label_transfer.npy', 't2_t1_label_transfer_en.npy',
#                 't2_t1_label_transfer_all.npy']

# scores_path = ['t2_t1_score.npy', 't2_t1_score_transfer_all.npy', 't2_t1_score_transfer1_self_learning.npy',
#                't2_t1_score_transfer1_all.npy','t2_t1_score_transfer1au_all.npy']
# labels_path = ['t2_t1_label.npy', 't2_t1_label_transfer_all.npy', 't2_t1_label_transfer1_self_learning.npy',
#                't2_t1_label_transfer1_all.npy','t2_t1_label_transfer1au_all.npy']

# scores_path = ['scores_out_unet_jac.npy','scores_out_unet_dic.npy', 'scores_out_unet_focl.npy']

# labels_path = ['labels_out_unet_jac.npy','labels_out_unet_dic.npy', 'labels_out_unet_focl.npy']

scores_path = ['t1_t2_score.npy', 't1_t2_score_transfer_en.npy',
                't1_t2_score_transfer_all.npy', 't1_t2_score_transfer1_all.npy','t1_t2_score_transfer1au_all.npy']
labels_path = ['t1_t2_label.npy',  't1_t2_label_transfer_en.npy',
                't1_t2_label_transfer_all.npy','t1_t2_label_transfer1_all.npy','t1_t2_label_transfer1au_all.npy']

# scores_path = ['scores_out_unet_jac.npy','scores_out_unet_dic.npy', 'scores_out_unet_focl.npy']

# labels_path = ['labels_out_unet_jac.npy','labels_out_unet_dic.npy', 'labels_out_unet_focl.npy']

path = '../results_restore'

idx = 0

for idx in range(0, len(scores_path)):
    score_out =  np.load(scores_path[idx])
    label_out =  np.load(labels_path[idx])

    auc_out = roc(label_out, score_out)
    precision, recall, thresholds = precision_recall_curve(label_out, score_out)
    average_precision = average_precision_score(label_out, score_out)
    print('AP is', average_precision)
    f1 = (precision * recall) / (precision + recall + 1e-6)
    diff = np.abs(precision-recall).tolist()
    # yuzhi_idx = np.argmin(diff)
    yuzhi_idx = np.argmax(f1)

    precision_val = precision[yuzhi_idx]
    recall_val = recall[yuzhi_idx]
    print(' recall star is', recall_val)
    print(' precision star is', precision_val)

    th = thresholds[yuzhi_idx]
    score_out = (score_out>th)*255

    F1 = f1_score(label_out, score_out/255)
    print('F1 is', F1)

    jacard_coefficent = jaccard_score(label_out, score_out/255)

    print('JACC is', jacard_coefficent)

    # score_out = score_out.astype(np.uint8)
    # score_out= np.reshape(score_out, [641,224,224])
    # label_out= np.reshape(label_out, [641,224,224])
    # label_out = (label_out*255).astype(np.uint8)

    # plt.imshow(score_out[0])
    # plt.imshow(label_out[0])

    # pp = 64
    # out_name = os.path.join(path,str(pp)+'gt.png')
    # scor_name = os.path.join(path,str(pp)+'_'+str(idx)+'.png')

    # cv2.imwrite(out_name, label_out[pp])
    # cv2.imwrite(scor_name, score_out[pp])

# '''evaluation test'''
# idx = 0
# data_pathes = '../RSDDs dataset/Type-I RSDDs dataset'
# valid_dataset = DefectDataset(data_pathes, istrain=False, debug=True)
# valid_loader = DataLoader(valid_dataset, batch_size=1, shuffle=False, num_workers=0)
# for i, data in enumerate(valid_loader, 0):
#     length = len(valid_loader)
#     inputs, labels, name = data
#     print(name, idx)
#     idx = idx + 1


"""973. K Closest Points to Origin (Difficulty: Medium).
https://leetcode.com/problems/k-closest-points-to-origin/

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k,
return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).

Example 1:
https://assets.leetcode.com/uploads/2021/03/03/closestplane1.jpg
Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].

Example 2:
Input: points = [[3,3],[5,-1],[-2,4]], k = 2
Output: [[3,3],[-2,4]]
Explanation: The answer [[-2,4],[3,3]] would also be accepted.

Constraints:
    1 <= k <= points.length <= 104
    -104 <= xi, yi <= 104"""
import heapq

class Solution973:
    def kClosest(self, points: list[list[int]], k: int) -> list[list[int]]:
        result = []
        hashmap = {}
        min_heap = [(point[0] ** 2) + (point[1] ** 2) for point in points]
        for i in range(len(min_heap)):
            hashmap[min_heap[i]] = points[i]

        heapq.heapify(min_heap)
        while k > 0:
            closest_point = heapq.heappop(min_heap)
            result.append(hashmap[closest_point])
            k -= 1

        return result

solution = Solution973()
print(solution.kClosest(points=[[1, 3], [-2, 2]], k=1))
print(solution.kClosest(points=[[3, 3], [5, -1], [-2, 4]], k=2))

Heap or Priority Queue/Problem 973 K Closest Points to Origin.py


# coding: utf-8

class MetaEnumType(type):
    def __init__(cls, name, bases, attrs):
        reverse_name, reverse_verbose, _by_name, _by_verbose = {}, {}, {}, {}
        for name, item in attrs.items():
            if not name.startswith('__'):
                if type(item) == tuple:
                    value, verbose = item
                else:
                    value = item
                    verbose = unicode(item)

                setattr(cls, name+'_verbose', verbose)
                setattr(cls, name+'_name', name)
                setattr(cls, name, value)
                reverse_name[value] = name
                reverse_verbose[value] = verbose
                _by_name[name] = value
                _by_verbose[verbose] = value

        # attrs: name, verbose
        setattr(cls, 'name', reverse_name)
        setattr(cls, 'verbose', reverse_verbose)

        # functions: get_name, verbose
        get_name = classmethod(lambda cls, v: reverse_name[v])

        def _get_verbose(cls, v):
            try:
                return reverse_verbose[v]
            except KeyError:
                raise Exception('KeyError: MetaEnum "%s" has no value "%s"!' % (cls.__name__, v))

        get_verbose = classmethod(_get_verbose)
        setattr(cls, 'get_name', get_name)
        setattr(cls, 'get_verbose', get_verbose)

        # by_name, by_verbose
        setattr(cls, 'by_name', staticmethod(lambda name: _by_name[name]))
        setattr(cls, 'by_verbose', staticmethod(lambda verbose: _by_verbose[verbose]))

        setattr(cls, 'verbose_by_int', staticmethod(lambda value: reverse_verbose[value]))
        # utilit functions: as_choices
        choices = [(k, v) for k, v in reverse_verbose.iteritems()]
        as_choices = staticmethod(lambda: choices)
        setattr(cls, 'as_choices', as_choices)

        # revesred (with_none)
        choices_vk = [(v, k) for k, v in reverse_verbose.iteritems()]
        as_choices_vk = staticmethod(lambda with_none=False: choices_vk if not with_none else [('', None)]+choices_vk)
        setattr(cls, 'as_choices_vk', as_choices_vk)

        # contains
        has_key = staticmethod(lambda key: key in reverse_name.keys())
        setattr(cls, 'has_key', has_key)

class MetaEnum(object):
    """
    example of use:
    >>> from metaenum import MetaEnum
    >>> class FOO(MetaEnum):
    ...    BAZ = (0, 'bazik')
    ...    BAR = 1
    >>> FOO.BAZ
    0
    >>> FOO.BAR
    1
    >>> FOO.BAZ_name
    'BAZ'
    >>> FOO.BAZ_verbose
    'bazik'
    >>> FOO.get_verbose(FOO.BAZ)
    'bazik'
    >>> FOO.get_verbose(FOO.BAR)
    None
    >>> FOO.as_choices()
    [(0, 'bazik'), (1, None)]
    >>> FOO.by_name('BAZ')
    0
    >>> FOO.by_verbose('bazik')
    1
    """
    __metaclass__ = MetaEnumType


#!/usr/bin/env python

import os
import sys
import time
import usb.core
import argparse
import matplotlib.pyplot as plt

VID             = 0x24aa
PID             = 0x4000
BUF             = [0] * 8
HOST_TO_DEVICE  = 0x40
DEVICE_TO_HOST  = 0xC0
TIMEOUT_MS      = 1000

def get_spectrum():
    print("sending ACQUIRE")
    dev.ctrl_transfer(HOST_TO_DEVICE, 0xad, 0, 0, BUF, TIMEOUT_MS)

    bytes_to_read = args.pixels * 2
    print(f"reading {bytes_to_read} bytes from bulk endpoint")
    data = dev.read(0x82, bytes_to_read)

    if len(data) != bytes_to_read:
        print("ERROR: read %d bytes" % len(data))
        sys.exit(1)

    spectrum = []
    for i in range(args.pixels):
        spectrum.append(data[i*2] | (data[i*2 + 1] << 8))

    return spectrum

################################################################################
# parse command-line arguments
################################################################################

parser = argparse.ArgumentParser()
parser.add_argument("--integration-time-ms", type=int, default=400, help="default 400")
parser.add_argument("--gain-db",             type=int, default=8, help="default 8")
parser.add_argument("--count",               type=int, default=1, help="how many spectra to take")
parser.add_argument("--delay-ms",            type=int, default=10, help="how long to delay between spectra (default 10)")
parser.add_argument("--throwaways",          type=int, default=2, help="how many throwaways to take (default 2)")
parser.add_argument("--pixels",              type=int, default=1920, help="default 1920")
parser.add_argument("--pixel-mode",          type=int, default=None, choices=[0,1,2,3], help="(optional, no default)")
parser.add_argument("--plot",                action="store_true", help="display graph")
parser.add_argument("--outfile",             type=str, help="save spectra")
args = parser.parse_args()

################################################################################
# connect
################################################################################

dev = usb.core.find(idVendor=VID, idProduct=PID)
if dev is None:
    print(f"No matching spectrometer found (VID 0x{VID:04x}, PID 0x{PID:04x})")
    sys.exit(1)

if os.name == "posix":
    dev.set_configuration()
    usb.util.claim_interface(dev, 0)

# print(dev)

################################################################################
# set acquisition parameters
################################################################################

print("sending SET_INTEGRATION_TIME_MS -> %d ms" % args.integration_time_ms)
dev.ctrl_transfer(HOST_TO_DEVICE, 0xb2, args.integration_time_ms, 0, BUF, TIMEOUT_MS)

gain_ff = args.gain_db << 8
print(f"sending GAIN_DB -> {args.gain_db} (FunkyFloat 0x{gain_ff:04x})")
dev.ctrl_transfer(HOST_TO_DEVICE, 0xb7, gain_ff, 0, BUF, TIMEOUT_MS)

if args.pixel_mode is not None:
    print(f"setting pixel mode {args.pixel_mode}")
    dev.ctrl_transfer(HOST_TO_DEVICE, 0xfd, args.pixel_mode, 0, BUF, TIMEOUT_MS)
    print("sleeping 1 sec for pixel mode to 'take'")
    time.sleep(1)

################################################################################
# collect spectra
################################################################################

spectra = []
for i in range(args.count + args.throwaways):
    spectrum = get_spectrum()
    if i > 0:
        print(f"sleeping {args.delay_ms}ms")
        time.sleep(args.delay_ms / 1000.0)

    if i < args.throwaways:
        print("dumping throwaway")
    else:
        spectra.append(spectrum)
        print("storing")

################################################################################
# process spectra
################################################################################

print("max = %d" % max(max(spectra)))
print("min = %d" % min(min(spectra)))
print("sum = %e" % sum([sum(spectrum) for spectrum in spectra]))

if args.outfile:
    print(f"writing {args.outfile}")
    with open(args.outfile, 'w') as f:
        for i in range(args.pixels):
            f.write("%s\n" % ', '.join([str(a[i]) for a in spectra]))

if args.plot:
    [plt.plot(a) for a in spectra]
    plt.title(f"integration time {args.integration_time_ms}ms, gain {args.gain_db}dB, pixel mode {args.pixel_mode}, count {args.count}")
    plt.show()