散列字符串列表元素并保存到新列表

时间:2019-03-21 15:46:40

标签: python python-3.x

我正在尝试使用100个名称,将每个名称哈希为8位,然后将其保存到新列表中。我知道使用8位很可能会导致冲突,我试图查看它们将以什么速率发生冲突,并且希望在我的论文中包含此代码段。

我相信我的逻辑还可以,只是语法导致了我的问题。任何帮助表示赞赏。

def video_analysis(request):

    framenumber = request.GET.get('f', '')
    print("framenumber ", framenumber)

    global frame2
    global tmp_path
    global myfile
    global filename
    global img1
    global img2
    global video_table, motionFlow_table
    video_table = []
    angles =[]
    motionFlow_table = []
    video_table = np.empty([30, 400, 400, 3], np.dtype('uint8'))
    motionFlow_table = np.empty([30, 400, 400, 3], np.dtype('uint8'))
    times =0

    if (request.session['doctor_id'] == ""):
        return redirect('login')

    times = times +1
    path = STATIC_PATH
    direct = request.session['directory']
    p_id = request.session['p_id']
    p_name = request.session['p_name']
    p_lastname = request.session['p_lastname']
    os.chdir(direct)
    print(direct)


    myfile = None
    if request.method == 'POST' and 'myfile' in request.FILES:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = myfile.name
        print(filename)
        if (not os.path.exists(direct + "\\" + myfile.name)):
            filename = fs.save(direct + "\\" + myfile.name, myfile)
            print(filename)
        path = direct + "\\" + myfile.name
        print(path)
        print(direct)
        request.session['path'] = path
        request.session['file'] = myfile.name
        print(myfile.name)
        uploaded_file_url = fs.url(filename) + "/static"
        print(uploaded_file_url)
        if request.session.has_key('path'):
            path = request.session['path']
            tmp_path = ""
            for i in range(0, len(path)):
                if (path[i] == "\\"):
                    tmp_path = tmp_path + '/'
                else:
                    tmp_path = tmp_path + path[i]


        print(tmp_path)
        print(myfile)
        if myfile != None:
                print("not empty")
        cap = cv2.VideoCapture(str(myfile))

        if (cap.isOpened() == False):
            print("Error opening video")

        begin_frame = 1
        count =1 #counter for frames
        ret, frame1 = cap.read()

        # Region of Interest - ROI
        template = frame1[150:250,0:100]

        video_table[count] = frame1  # save the video into array
        cv2.imwrite(('frame %d.jpg' % count), frame1)
        original = frame1
        grayimg_1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
        cv2.imwrite('frame1gray.jpg', grayimg_1)

        gray_img, topleft, bottomright = template_matching(grayimg_1,template )
        print("topleft",topleft)
        print("bottomright",bottomright)

        cv2.imwrite("gray1.jpeg", grayimg_1)

        if np.shape(frame1) == (): 
            print ("empty frame")

        hsv = np.zeros_like(frame1)
        hsv[..., 1] = 255



        fourcc = cv2.VideoWriter_fourcc(*'DIVX')
        fourcc1 = cv2.VideoWriter_fourcc(*'DIVX')
        out = cv2.VideoWriter('output.avi', fourcc, 25.0, (500, 400))
        out1 = cv2.VideoWriter('output1.avi', fourcc1, 25.0, (500, 400))

        while (cap.isOpened()):
            ret, frame2 = cap.read()
            count =count+1

            if ret != True:
             break;

            video_table[count] = frame2  # save video frames into table
            cv2.imwrite(('frame %d.jpg' % count), frame2)
            grayimg_2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
            cv2.imwrite("gray %d.jpeg", grayimg_2)

            gray_img, topleft, bottomright = template_matching(grayimg_2, template)


            # Computes a dense optical flow using the Gunnar Farneback's algorithm.
            flow = cv2.calcOpticalFlowFarneback(grayimg_1, grayimg_2, None, 0.5, 3, 15, 3, 5, 1.2, 0)

            test_img = draw_flow(gray_img, flow,topleft,bottomright)
            cv2.imwrite(("motionFlow_img %d.jpg" %count), motionFlow_table[count])


            # Calculate the magnitude and angle of 2D vectors.
            mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])


            angles.append(ang)

            k = cv2.waitKey(30) & 0xff
            if k == 27:
                break

            cv2.imwrite('opticalfb.jpeg', frame2)
            grayimg_1 = grayimg_2

        print("number of frames: ", count)
        out.release()
        out1.release()
        cv2.destroyAllWindows()


        cv2.waitKey(0) #press something to continue
        end_frame = count


        # Video Properties
        # number of frames
        video_length = cap.get(cv2.CAP_PROP_FRAME_COUNT)
        total_frames = int(video_length)
        print("total" , total_frames)

        #frame rate
        frame_rate = float(cap.get(cv2.CAP_PROP_FPS))
        print(frame_rate)
        #video duration
        duration = round(float(video_length / frame_rate), 2)
        print(duration)


        data = np.array(ang)
        name_of_file1 = filename.split("/")[-1]

        name_of_file1 = p_id + "/" + "frame 1.jpg"
        print(name_of_file1)

        return render(request, 'video_analysis.html', {     'video_frame' : name_of_file1,
                                                            'firstframe' : name_of_file1,
                                                            'video': myfile,
                                                            'video_path':tmp_path,
                                                            'beginframe': int(begin_frame),
                                                            'endframe': int(end_frame),
                                                            'video_duration': duration})

1 个答案:

答案 0 :(得分:2)

在不影响逻辑的情况下,要使代码正常工作,您需要替换以下行:

for i in list:
    newlist = hash(list[i] % 10**8)

使用

for i in list:
    newlist.append(hash(i) % 10**8)

一些澄清:

在Python中,您可以在任何列表对象上使用.append()将元素添加到该列表的末尾。在这种情况下,您将用循环内的元素填充上面初始化的空列表。此外,除了例如经典的Java循环,在Python中,您可以直接遍历列表,这样i每次都引用列表中的另一个元素。因此,无需每次尝试以某个索引访问列表。希望这会有所帮助!