Пример #1
0
def upload():
    # check if user logged_in
    if not session['logged_in']:
        return render_template('home.html')

    # once logged_in, user is able to store images to his own folder
    # under image_repo directory
    tmp = 'image_repo/' + session['username'] + '/'
    savePath = os.path.join(SER_ROOT, tmp)
    if not os.path.isdir(savePath):
        os.mkdir(savePath)
    else:
        print("Failed to create directory\n")

    item = request.files.getlist('file')
    if len(item) == 0:
        return render_template('uploadImage.html')

    # set upload time
    for image in request.files.getlist('file'):
        filename = image.filename
        print(filename.split('.')[1])
        if filename.split('.')[1] in ['jpg', 'png', 'jpeg']:
            image.save(savePath + filename)
            os.utime(savePath + filename, None)

    files = os.listdir(savePath)
    s = []
    for file in files:
        s.append(str(file) + '\n')
        photoName = savePath + '/' + file
        cut.cut(photoName)
    return render_template("complete.html")
Пример #2
0
def main(origin_dir, target_dir):
    dir_name = basename(origin_dir)
    # handle_video(origin_dir, target_dir)
    target_dir = os.path.join(target_dir, dir_name)

    output_dir = os.path.join(target_dir, 'cluster', 'output')
    if not os.path.exists(output_dir):
        makedirs(output_dir)

    cut([join(target_dir, d) for d in listdir(target_dir) if d != 'cluster'])

    do_cluster(os.path.join(target_dir, 'cluster'))
Пример #3
0
def balance(graph):
    '''parame: graph, a DAG its.__class__ == nx.DiGraph
       return: r,     removed edges set so makr the input graph a b-structure
    '''
    # 只处理整数形式的图,每一个整数对应的节点可以在后面查到
    # 输入进来的图应该是连通的,如果存在非连通图,minimum_edge_cut就会产生问题
    assert nx.is_directed_acyclic_graph(graph),\
        "The target graph you want to banlance is not a DAG"
    r = []  # removed set
    if check(graph):
        return r
    #非B-Stucture时,一直循环下去
    # BUGY: 如果cs为空呢,那么不可能有两个图返回来,这时候怎么办
    print "\nCutting Graph"
    cs, g1, g2 = cut(graph)
    r = balance(g1) + balance(g2) + cs
    csl = []
    for eachEdge in cs:
        under_check_graph = graph.copy()
        under_check_graph.remove_edges_from(r)
        under_check_graph.add_edges_from(csl)
        under_check_graph.add_edge(eachEdge[0], eachEdge[1])
        if check(under_check_graph):
            print "Edge: %s added back" % str(eachEdge)
            csl.append(eachEdge)
            graph.add_edge(eachEdge[0], eachEdge[1])
    for eachEdge in csl:
        r.remove(eachEdge)
    print "Removed Edge Set: %s" % str(r)
    return r
Пример #4
0
def balance(graph):
    '''parame: graph, a DAG its.__class__ == nx.DiGraph
       return: r,     removed edges set so makr the input graph a b-structure
    '''
    # 只处理整数形式的图,每一个整数对应的节点可以在后面查到
    # 输入进来的图应该是连通的,如果存在非连通图,minimum_edge_cut就会产生问题
    assert nx.is_directed_acyclic_graph(graph),\
        "The target graph you want to banlance is not a DAG"
    r = [] # removed set
    if check(graph):
        return r
    #非B-Stucture时,一直循环下去
    # BUGY: 如果cs为空呢,那么不可能有两个图返回来,这时候怎么办
    print "\nCutting Graph"
    cs, g1, g2 = cut(graph) 
    r = balance(g1) + balance(g2) + cs
    csl = []
    for eachEdge in cs:
        under_check_graph = graph.copy()
        under_check_graph.remove_edges_from(r)
        under_check_graph.add_edges_from(csl)
        under_check_graph.add_edge(eachEdge[0],eachEdge[1])
        if check(under_check_graph):
            print "Edge: %s added back" % str(eachEdge)
            csl.append(eachEdge)
            graph.add_edge(eachEdge[0],eachEdge[1])
    for eachEdge in csl:
        r.remove(eachEdge)
    print "Removed Edge Set: %s" % str(r)
    return r
Пример #5
0
def start(input, output):

    valArr = np.zeros([ROW, COL])

    with open(input, 'rb') as f:
        for i in range(ROW):
            for j in range(COL):
                val = list(struct.unpack(">1f", f.read(4)))[0]
                valArr[i][j] = float(val)

    interpVal = U.interp(valArr, tX, tY)

    valTable = interpVal.flatten()

    img = Image.new("RGBA", resolution + 1, (0, 0, 0, 0))

    length = len(latTable)

    for i in range(length):

        val = valTable[i]

        img.putpixel(mercatorMap[i], COLOR.color1(val))

    img = CUT.cut(img)

    img = LEGEND.draw(img, 'l1')

    img.save(output + ".png", 'PNG')
Пример #6
0
def WaitUntil(waitImage, beforeDelay, afterDelay):
    Delay(beforeDelay)
    while True:
        srcImage = cut(savePicture=False)
        pos = ac.find_template(srcImage, waitImage)
        if pos is not None and pos['confidence'] > 0.9:
            break
        Delay(1.0)
    Delay(afterDelay)
Пример #7
0
def main(target_dir):
    handle_video(target_dir)
    # target_dir = os.path.join(target_dir, os.path.basename(origin_dir))
    for f in os.listdir(target_dir):
        print('Task: {} start'.format(f))
        try:
            scenario_dir = os.path.join(target_dir, f)
            output_dir = os.path.join(scenario_dir, 'cluster', 'output')
            cut(scenario_dir, output_dir)
            cluster_dir = os.path.join(scenario_dir, 'cluster', 'cluster')
            makedirs(cluster_dir)
            do_cluster(os.path.join(scenario_dir, 'cluster'))
            zip_file = os.path.join(
                scenario_dir, '{}.zip'.format(os.path.basename(scenario_dir)))
            do_zip(zip_file, cluster_dir)
        except Exception as e:
            print('Task: {} error'.format(f))
            print(e)
Пример #8
0
def CLCS(A, B):
    bestLCS = 0
    for i in range(len(A)):
        currLCS = LCS(cut(A, i), B)
        if currLCS > bestLCS:
            bestLCS = currLCS
            if bestLCS == len(A):  # catches a perfect match
                return bestLCS
    return bestLCS
Пример #9
0
def wait_until_next_phase():
    while True:
        src_image = cut(save_picture=False)
        pos = ac.find_template(
            src_image, master_image if remain_phase_number > 0 else ban_image)
        if pos is not None and pos['confidence'] > 0.95:
            break
        等待(1.0)
    等待(0.2 if remain_phase_number > 0 else 1.0)
Пример #10
0
def texture_transfer(texture, target, patchsize, overlap, tol):

    outsize = size(target)
    outsize = [outsize[1], outsize[2]]

    xtrim = patchsize - (outsize[1] - ((patchsize - overlap) * math.floor(
        (outsize[1] - patchsize) /
        (patchsize - overlap)) + 1 + patchsize - overlap))
    ytrim = patchsize - (outsize[0] - ((patchsize - overlap) * math.floor(
        (outsize[0] - patchsize) /
        (patchsize - overlap)) + 1 + patchsize - overlap))

    outsize_ = outsize
    outsize_[0] = outsize_[0] + ytrim
    outsize_[1] = outsize_[1] + xtrim

    if (size(target)[3] == 1):
        imout = np.zeros((outsize_))

    else:
        imout = np.zeros(
            (int(outsize_[0]), int(outsize_[1]), int(size(target)[3])))

    for i in xrange(0, outsize_[0] - patchsize + 1, patchsize - overlap):
        print i
        for j in xrange(0, outsize_[1] - patchsize + 1, patchsize - overlap):
            if (i == 0 and j == 0):
                pos = find_mindelta(texture, target, [0, 0], patchsize, tol)
                imout[i:i + patchsize - 1, j:j + patchsize -
                      1, :] = texture[int(pos[1]):int(pos[1]) + patchsize - 1,
                                      int(pos[2]):int(pos[2]) + patchsize -
                                      1, :]

            else:
                if (i > outsize[0] - patchsize + 1):
                    i_new = outsize[0] - patchsize + 1

                else:
                    i_new = copy(i)

                if (j > outsize[1] - patchsize + 1):
                    j_new = outsize[1] - patchsize + 1

                else:
                    j_new = copy(j)

                currentpos = [i_new, j_new]

                patchpos = find_mindelta(texture, target, currentpos,
                                         patchsize, tol)

                imout = cut(texture, patchsize, overlap, imout, patchpos,
                            currentpos)

    # imout=imout[1:outsize[1],1:outsize[2],:]
    return imout
Пример #11
0
def bot():
    token = read_token()
    bible = cut()
    client = discord.Client()

    @client.event
    async def on_ready():
        channel = client.get_channel(ID)
        # await channel.send(bible)
        if (len(bible) > 2000):
Пример #12
0
def build(do_publish=0):
    print("Build")
    print("-----")

    outfile = 'hardware.json'
    oldfile = 'backup.json'

    print("Backup current json...")
    oldjso = None
    if os.path.isfile(outfile) and not os.path.isfile(oldfile):
        os.rename(outfile, oldfile)

    errorlevel = 0

    errorlevel += parse_machines()

    if errorlevel == 0:
        errorlevel += vitamins()
    if errorlevel == 0:
        errorlevel += cut()
    if errorlevel == 0:
        errorlevel += printed()
    if errorlevel == 0:
        errorlevel += assemblies()
    if errorlevel == 0:
        errorlevel += machines()

    if errorlevel == 0:
        errorlevel += guides()

    catalogue()

    if errorlevel == 0 and do_publish > 0:
        publish()

    # if everything is ok then delete backup - no longer required
    if errorlevel == 0:
        os.remove(oldfile)

    try:
        if sys.platform == "darwin":
            check_output([
                'osascript', '-e',
                'display notification "Build Complete" with title "Build Process"'
            ])
    except:
        print("Exception running osascript")

    print("")
    print("==============")
    print("Build Complete")

    return errorlevel
Пример #13
0
def build(do_publish=0):
    print("Build")
    print("-----")

    outfile = 'hardware.json'
    oldfile = 'backup.json'

    print("Backup current json...")
    oldjso = None
    if os.path.isfile(outfile) and not os.path.isfile(oldfile):
        os.rename(outfile, oldfile)

    errorlevel = 0

    errorlevel += parse_machines()

    if errorlevel == 0:
        errorlevel += vitamins()
    if errorlevel == 0:
        errorlevel += cut()
    if errorlevel == 0:
        errorlevel += printed()
    if errorlevel == 0:
        errorlevel += assemblies()
    if errorlevel == 0:
        errorlevel += machines()

    if errorlevel == 0:
        errorlevel += guides()

    catalogue();

    if errorlevel == 0 and do_publish > 0:
        publish()


    # if everything is ok then delete backup - no longer required
    if errorlevel == 0:
        os.remove(oldfile)

    try:
        if sys.platform == "darwin":
            check_output(['osascript','-e','display notification "Build Complete" with title "Build Process"'])
    except:
        print("Exception running osascript")

    print("")
    print("==============")
    print("Build Complete")

    return errorlevel
Пример #14
0
def train(n):
    k = 16
    import wave
    code = []

    for i in range(n):
        wav_file=wave.open('{}'.format(i+1) + '.wav')
        raw_frames = wav_file.readframes(-1)
        num_frames = wav_file.getnframes()
        num_channels = wav_file.getnchannels()
        sample_rate = wav_file.getframerate()
        sample_width = wav_file.getsampwidth()
        temp_buffer = np.empty((num_frames, num_channels, 4), dtype=np.uint8)
        raw_bytes = np.frombuffer(raw_frames, dtype=np.uint8)
        temp_buffer[:, :, :sample_width] = raw_bytes.reshape(-1, num_channels, 
                                                    sample_width)
        temp_buffer[:, :, sample_width:] = \
            (temp_buffer[:, :, sample_width-1:sample_width] >> 7) * 255
        frames = temp_buffer.view('<i4').reshape(temp_buffer.shape[:-1])
        
        #sample_rate = wav_file.getframerate()
        sample_rate = 16000;
        signal=frames[::3,0]
        sample_rate, signal = cut.cut(sample_rate, signal)
#        sample_rate, signal = scipy.io.wavfile.read('{}'.format(i+1) + '.wav')
        v = mfcc(signal, sample_rate)

        code.append(vqlbg(v, k))
        print(i)


    if n == 3:
        d1 = disteu(code[0], code[1])
        d2 = disteu(code[1], code[2])
        d3 = disteu(code[2], code[0])

        dk = []
        dk.append(sum(d1.min(1)) / d1.shape[0])
        dk.append(sum(d2.min(1)) / d2.shape[0])
        dk.append(sum(d3.min(1)) / d3.shape[0])

        dmax = max(dk)
        dmin = min(dk)
    else:
        dmax = 0
        dmin = 0

    return code, dmax, dmin
Пример #15
0
def scan(root, debug):
    # 文件名正则
    filePattern = re.compile("^[a-zA-Z0-9]+$")
    # 上衣文件名正则
    clothingPattern = re.compile(".*上衣")
    clothingCount = 0
    pantsCount = 0
    # 先删除文件
    for dp, dn, fs in os.walk(root):
        for f in fs:
            # 分割图像并进行存储
            filename = f.split('.')[0]
            srcPath = os.path.join(dp, f)
            if not filePattern.match(filename):
                os.remove(srcPath)
    for dp, dn, fs in os.walk(root):
        for f in fs:
            # 分割图像并进行存储
            filename = f.split('.')[0]
            srcPath = os.path.join(dp, f)
            if filePattern.match(filename):
                cutPath = os.path.join(dp, "%s_cut.jpg" % filename)
                maskPath = os.path.join(dp, "%s_mask.jpg" % filename)
                if clothingPattern.match(srcPath):
                    isClothing = True
                    clothingCount = clothingCount + 1
                else:
                    isClothing = False
                    pantsCount = pantsCount + 1
                print '---->'
                print '%s is cutting' % srcPath
                image = cv2.imread(srcPath)
                mask, cutImage = cut(image,
                                     isClothing,
                                     dp,
                                     filename,
                                     isDebug=debug)
                cv2.imwrite(cutPath, cutImage)
                cv2.imwrite(maskPath, mask)
                print '<----'
            else:
                os.remove(srcPath)
    print '----------completed!    ----------'
    print '----------clothings: %d ----------' % clothingCount
    print '----------pants:     %d ----------' % pantsCount
def build(do_publish=0):
    print("Build")
    print("-----")

    outfile = 'hardware.json'
    oldfile = 'backup.json'

    print("Backup current json...")
    oldjso = None
    if os.path.isfile(outfile) and not os.path.isfile(oldfile):
        os.rename(outfile, oldfile)

    errorlevel = 0

    errorlevel += parse_machines()

    if errorlevel == 0:
        errorlevel += vitamins()
    if errorlevel == 0:
        errorlevel += cut()
    if errorlevel == 0:
        errorlevel += printed()
    if errorlevel == 0:
        errorlevel += assemblies()
    if errorlevel == 0:
        errorlevel += machines()

    if errorlevel == 0:
        errorlevel += guides()

    catalogue();

    if errorlevel == 0 and do_publish > 0:
        publish()


    # if everything is ok then delete backup - no longer required
    if errorlevel == 0:
        os.remove(oldfile)

    return errorlevel
Пример #17
0
def build(do_publish=0):
    print("Build")
    print("-----")

    outfile = 'hardware.json'
    oldfile = 'backup.json'

    print("Backup current json...")
    oldjso = None
    if os.path.isfile(outfile) and not os.path.isfile(oldfile):
        os.rename(outfile, oldfile)

    errorlevel = 0

    errorlevel += parse_machines()

    if errorlevel == 0:
        errorlevel += vitamins()
    if errorlevel == 0:
        errorlevel += cut()
    if errorlevel == 0:
        errorlevel += printed()
    if errorlevel == 0:
        errorlevel += assemblies()
    if errorlevel == 0:
        errorlevel += machines()

    if errorlevel == 0:
        errorlevel += guides()

    catalogue()

    if errorlevel == 0 and do_publish > 0:
        publish()

    # if everything is ok then delete backup - no longer required
    if errorlevel == 0:
        os.remove(oldfile)

    return errorlevel
Пример #18
0
def test(name, code):
    import wave
    wav_file = wave.open(name + '.wav')
    raw_frames = wav_file.readframes(-1)
    num_frames = wav_file.getnframes()
    num_channels = wav_file.getnchannels()
    sample_rate = wav_file.getframerate()
    sample_width = wav_file.getsampwidth()
    temp_buffer = np.empty((num_frames, num_channels, 4), dtype=np.uint8)
    raw_bytes = np.frombuffer(raw_frames, dtype=np.uint8)
    temp_buffer[:, :, :sample_width] = raw_bytes.reshape(
        -1, num_channels, sample_width)
    temp_buffer[:, :, sample_width:] = \
        (temp_buffer[:, :, sample_width-1:sample_width] >> 7) * 255
    frames = temp_buffer.view('<i4').reshape(temp_buffer.shape[:-1])

    #sample_rate = wav_file.getframerate()/3
    sample_rate = 16000
    signal = frames[::3, 0]
    sample_rate, signal = cut.cut(sample_rate, signal)
    v = mfcc(signal, sample_rate)

    distmin = float('inf')
    dist = 0

    for i in range(len(code)):
        d = disteu(v, code[i])
        dist += sum(d.min(1)) / d.shape[0]
    dist = dist / len(code)
    # dist = sum(d.min(1)) / d.shape[0]
    #
    # if dist < distmin:
    #     distmin = dist

    print(dist)

    if dist < 4.0:
        return True
    else:
        return False
Пример #19
0
    def detect(self,
               img,
               min_size=40,
               factor=0.709,
               score_threshold=[0.5, 0.5, 0.5],
               iou_threshold=[0.5, 0.7, 0.7, 0.7]):
        '''

        :param img: numpy array (shape [height, width, 3] )
        :return: boxes: numpy array (shape [N, 5])
                                [h0, w0, h1, w1, score]
                 landmarks: numpy array (shape [N, 10]
                            [h_leye, h_reye, h_nose, h_lmouth, h_rmouth,
                             w_leye, w_reye, w_nose, w_lmouth, w_rmouth]
        '''
        # Stage 1
        h, w, _ = img.shape
        min_l = min(h, w)
        m = 12. / min_size
        min_l = min_l * m
        scales = []
        while min_l >= 12:
            scales.append(m)
            min_l *= factor
            m *= factor

        proposals_total = np.zeros((0, 9), dtype=np.float32)
        for scale in scales:
            hs = int(np.round(h * scale))
            ws = int(np.round(w * scale))
            img_resize = cv2.resize(img, (ws, hs),
                                    interpolation=cv2.INTER_LINEAR)
            img_resize = (img_resize - 127.5) * 0.0078125
            img_resize = img_resize[np.newaxis, :, :, :]
            try:
                cls_prob, bbox_reg = self.pnet.predict(img_resize)
            except:
                continue
            prob = cls_prob[..., 1]
            idx_pos = np.where(prob >= score_threshold[0])
            prob_pos = prob[idx_pos].reshape([-1, 1])
            h0 = idx_pos[1].reshape([-1, 1])
            w0 = idx_pos[2].reshape([-1, 1])
            bbox_pos = np.concatenate((h0, w0, h0 + 5.5, w0 + 5.5), axis=1)
            bbox_pos = np.round(bbox_pos * 2 / scale)
            bbox_reg_pos = bbox_reg[idx_pos]
            proposals = np.concatenate((bbox_pos, prob_pos, bbox_reg_pos),
                                       axis=1)
            proposals = proposals[nms(proposals, iou_threshold[0])]
            proposals_total = np.concatenate((proposals_total, proposals),
                                             axis=0)
        if len(proposals_total) == 0:
            return (np.zeros(
                (0, 5), dtype=np.float32), np.zeros((0, 10), dtype=np.float32))

        proposals_total = proposals_total[nms(proposals_total,
                                              threshold=iou_threshold[1])]
        proposals_total = bbreg(proposals_total)

        # Stage 2
        proposals_total = rerec(proposals_total)
        boxes = proposals_total[:, 0:4].astype(np.int32)
        input = cut(img, boxes, h, w, 24)
        input = (input - 127.5) * 0.0078125
        try:
            cls_prob, bbox_reg = self.rnet.predict(input)
        except:
            return (np.zeros(
                (0, 5), dtype=np.float32), np.zeros((0, 10), dtype=np.float32))

        prob = cls_prob[..., 1]
        idx_pos = np.where(prob >= score_threshold[1])
        prob_pos = prob[idx_pos].reshape([-1, 1])
        bbox_pos = boxes[idx_pos]
        bbox_reg_pos = bbox_reg[idx_pos]
        proposals_total = np.concatenate((bbox_pos, prob_pos, bbox_reg_pos),
                                         axis=1)
        if len(proposals_total) == 0:
            return (np.zeros(
                (0, 5), dtype=np.float32), np.zeros((0, 10), dtype=np.float32))

        proposals_total = proposals_total[nms(proposals_total,
                                              threshold=iou_threshold[2])]
        proposals_total = bbreg(proposals_total)

        # Stage 3
        proposals_total = rerec(proposals_total)
        boxes = proposals_total[:, 0:4].astype(np.int32)
        input = cut(img, boxes, h, w, 48)
        input = (input - 127.5) * 0.0078125
        try:
            cls_prob, bbox_reg, landmark_reg = self.onet.predict(input)
        except:
            return (np.zeros(
                (0, 5), dtype=np.float32), np.zeros((0, 10), dtype=np.float32))

        prob = cls_prob[..., 1]
        idx_pos = np.where(prob >= score_threshold[2])
        prob_pos = prob[idx_pos].reshape([-1, 1])
        bbox_pos = boxes[idx_pos]
        # refine landmark
        height = bbox_pos[:, 2:3] - bbox_pos[:, 0:1] + 1
        width = bbox_pos[:, 3:4] - bbox_pos[:, 1:2] + 1
        landmark = landmark_reg[idx_pos]
        landmark[:,
                 0:5] = np.round(bbox_pos[:, 0:1] + landmark[:, 0:5] * height)
        landmark[:,
                 5:10] = np.round(bbox_pos[:, 1:2] + landmark[:, 5:10] * width)
        bbox_reg_pos = bbox_reg[idx_pos]
        proposals_total = np.concatenate((bbox_pos, prob_pos, bbox_reg_pos),
                                         axis=1)
        if len(proposals_total) == 0:
            return (np.zeros(
                (0, 5), dtype=np.float32), np.zeros((0, 10), dtype=np.float32))

        proposals_total = bbreg(proposals_total)
        idx_keep = nms(proposals_total, threshold=iou_threshold[2], type='Min')

        return proposals_total[idx_keep][:, 0:5], landmark[idx_keep]
Пример #20
0
def DOS():
    W, H, N, RECTANGLES = di.Read()
    RECTANGLES = u.merge_sort(RECTANGLES)
    ORDER = 1
    CANVAS = c.Canvas(0, 0, W, H, ORDER)
    cu.cut(W, H, N, RECTANGLES, CANVAS, ORDER)
Пример #21
0
import numpy
import random
import matplotlib
matplotlib.use('pdf')
import matplotlib.pyplot as plt
import randvec as rd
import cellmain as cell
import rulesmain as rul
import plotmain as plm
import cut
import big

#M=512#liczba wierszy
#N=256 #liczba kolumn

cutout = cut.cut(112, 450)
#rd.setgen(A, N, vec)
BG = cut.findbg(cut.reduce(cutout, 100, 240))
#cutout = cut.cut(112, 0)
#vec=big.put(BG, cut.reduce(cutout, 75, 240))
#N=len(vec)
M = 100
A = numpy.zeros((M, N), dtype='i')  #macierz MxN inicjowana zerami
#rd.setgen(A, N, vec)
rd.randgen(A, N)

#for rlnbr in range(1,128):
rule = rul.rules(111)
cell.evolve(A, N, M, rule)
plm.plotspec(A, "show")
Пример #22
0
def 宝具(user, 手动选卡=False, 敌对目标=0, 选卡策略=[]):
    global remain_phase_number
    if 敌对目标 > 0:
        tap_key('234'[敌对目标 - 1], 普通操作时间)
    tap_key('\n', 进入选卡界面时间)
    index = 查找从者(user)
    # 识别5张牌都是啥
    # 5张牌在标准化图片(992*611)上的位置:
    # (10+200X,300)-(190+200X,5320),X=0,1,2,3,4
    if 自动选卡策略:
        src_image = cv2.resize(cut(save_picture=False), (992, 611))
        found_card_list = []
        for i in range(5):
            card_area_image = src_image[300:520, 10 + 200 * i:190 + 200 * i]
            found = '未定义-未定义'
            for servant_name in 阵容[:3]:
                if servant_name != '':
                    for color in ['红', '蓝', '绿']:
                        for test_image in 阵容卡组[servant_name][color]:
                            pos = ac.find_template(card_area_image, test_image)
                            # 这里有一个助战图标的问题
                            if pos is not None and pos['confidence'] > 0.8:
                                found = '%s-%s' % (servant_name, color)
                                break
                                break
                                break
            found_card_list.append(found)

    print('检测结果:')
    print(found_card_list)

    if not 手动选卡:
        result = []
        if 自动选卡策略:
            for 策略 in 选卡策略:
                # 试图匹配策略
                result = 选卡匹配(策略, found_card_list)
                if len(result) > 0:
                    break
        if len(result) == 0:
            result = ['WER'[index], 'S', 'D']
        tap_key(result[0], 普通操作时间)
        tap_key(result[1], 普通操作时间)
        if not 自动选卡策略:
            tap_key(result[2], treasure_time(user) + 换面时间)
        else:
            tap_key(result[2], 普通操作时间)
            remain_phase_number -= 1
            print('剩余面数:%d' % remain_phase_number)
            wait_until_next_phase()
            if remain_phase_number <= 0:
                remain_phase_number = 3
    else:
        tap_key('WER'[index], 普通操作时间)
        等待操作()
        等待(treasure_time(user) + 换面时间)
    if user == '大英雄':
        阵容[index] = 阵容[3]
        阵容[3] = 阵容[4]
        阵容[4] = 阵容[5]
        阵容[5] = ''
Пример #23
0
def build(argv):

    doCatalogue = True
    doQuick = False
    doPublish = False
    try:
        opts, args = getopt.getopt(argv, "hcqp", [])
    except getopt.GetoptError:
        print 'build.py -h -c -q -p'
        print ''
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'Usage: -h -c -q -p'
            print ''
            print '  -c   Skip catalogue'
            print '  -p   Publish: auto commit and push to git'
            print '  -q   Quick build - skip assemblies, guide and catalogue'
            sys.exit()
        if opt in ("-c"):
            doCatalogue = False
        if opt in ("-q"):
            doQuick = True
            doCatalogue = False
        if opt in ("-p"):
            doPublish = True

    print("Build")
    print("-----")

    outfile = 'hardware.json'
    oldfile = 'backup.json'

    print("Backup current json...")
    oldjso = None
    if os.path.isfile(outfile) and not os.path.isfile(oldfile):
        os.rename(outfile, oldfile)

    errorlevel = 0

    errorlevel += parse_machines()

    if errorlevel == 0:
        errorlevel += vitamins()
    if errorlevel == 0:
        errorlevel += cut()
    if errorlevel == 0:
        errorlevel += printed()
    if errorlevel == 0 and not doQuick:
        errorlevel += assemblies()
    if errorlevel == 0:
        errorlevel += machines()

    if errorlevel == 0 and not doQuick:
        errorlevel += guides()

    if doCatalogue and not doQuick:
        catalogue()

    if errorlevel == 0 and doPublish > 0:
        publish()

    # if everything is ok then delete backup - no longer required
    if errorlevel == 0:
        os.remove(oldfile)

    try:
        if sys.platform == "darwin":
            check_output([
                'osascript', '-e',
                'display notification "Build Complete" with title "Build Process"'
            ])
    except:
        print("Exception running osascript")

    print("")
    print("==============")
    print("Build Complete")

    return errorlevel
Пример #24
0
def main():
    best_score = 0

    # Load all stations from the csv file
    skip = False
    stations_data = load_data("data/StationsNationaal.csv", skip)

    # Prompt user for necessary input
    user_choices = user_interface(stations_data)

    # Load the connections data from the csv file (Heel Nederland or Noord- en
    # Zuid Holland), skipping a station if necessary
    data_list = load_data(user_choices["data"], user_choices["skip"])

    for _ in range(user_choices["attempts"]):
        # Load all stations as objects into a dictionary
        stations_objects = load_stations(data_list, stations_data)

        # Load all connections into a dictionary
        connection_objects = load_connections(
            data_list, stations_objects, user_choices["change_connections"])

        # Generate a random solution with chosen heuristics
        solution = random_solution(stations_objects, connection_objects,
                                   user_choices)

        # Run the heuristic of "cutting" trains, if the user chose this option
        if user_choices["cut_connections"]:
            solution = cut(solution)

        # Run the heuristic of "pasting" trains, if the user chose this option
        if user_choices["paste_connections"]:
            solution = paste(solution, user_choices["max_minutes"])

        # Delete empty trains from solution
        solution = delete_trains(solution)

        # Calculate the K of a solution with the given function
        score = calculate(solution)

        # Set score to new values
        if score > best_score:
            best_solution = solution
            best_score = score

    # Open outputfile
    f = open("output.csv", "w")
    f.write("random:\ntrein, lijnvoering\n")

    counter = 0

    # Write random solution to outputfile
    for train in best_solution["trains"]:
        counter += 1
        f.write(f'trein_{counter}, "{train}"\n')
    f.write(f"SCORE:{best_score}\n\n")
    f.close()

    # If simulated annealing is chosen
    if user_choices["sim_annealing"] == True:
        best_solution = simulated_annealing(solution, stations_objects,
                                            user_choices)

        # If heuristic cut is chosen
        if user_choices["SA_cut_connections"]:
            best_solution = cut(best_solution)

        best_solution = delete_trains(best_solution)
        better_score = calculate(best_solution)

        # Open outputfile
        f = open("output.csv", "a+")
        f.write("simulated annealing:\ntrein, lijnvoering\n")
        counter = 0

        # Write simulated annealing solution to outputfile
        for train in best_solution["trains"]:
            counter += 1
            f.write(f'trein_{counter}, "{train}"\n')
        f.write(f"SCORE:{better_score}\n\n")
        f.close()

    # Draw the map
    if user_choices["data"] == "data/ConnectiesHolland.csv":
        draw_train_holland(best_solution, stations_objects)
    else:
        draw_train(best_solution, stations_objects)
Пример #25
0
# -*- coding: utf-8 -*-

# 每次将模拟器滑到适当的位置,然后cmd里敲回车
# 完成截图之后继续下一次操作

from cut import cut
from processor import process_cut
from pywinauto.win32functions import SetForegroundWindow, GetForegroundWindow

print('截图助手已启动')
print('输入已进行的次数:')
op = input()
try:
    op = int(op)
except ValueError:
    op = 0

while True:
    print('已完成%d次截图,回车以开始下一次……' % op)
    input()
    original_window = GetForegroundWindow()
    cut()
    # process_cut(start_index=op*5)
    SetForegroundWindow(original_window)
    op += 1
Пример #26
0
# coding: utf8
import cv2
import numpy as np
import cut
image = cv2.imread('./images/13883/上衣/57f7cdb0f90a8310f062b13d.jpg')
rows, cols, _ = image.shape
resized = cv2.pyrDown(image, (rows / 2, cols / 2))
blured = cv2.medianBlur(resized, 3)

cutMask, cutImage = cut.cut(image, True, './test', 'pure', isDebug=True)

cv2.imshow('mask', cutMask)
cv2.waitKey(0)
cv2.imshow('cutImage', cutImage)
cv2.waitKey(0)
Пример #27
0
def appliquer_changements(id):
    form = Validate_form(request.form)
    cur = mysql.connection.cursor()
    result = cur.execute("SELECT id, nom FROM sample ")
    objets=cur.fetchall()
    cur.close()

    # Dictionnaire pour envoyer les infos a la page html
    dict={}
    dict['items']=objets
    dict['form']=form
    dict['tempo']=form

    # On récupere les infos depuis notre base de donnée pour les afficher
    cur = mysql.connection.cursor()
    result=cur.execute("SELECT titre,artiste,doc FROM musique WHERE id=%s ",[id])
    item=cur.fetchone()
    cur.close()
    
    dict['doc']= item['doc']
    dict['titre']=item['titre']
    dict['id']=id
    dict['tempo'] = 0
    if request.method == 'POST':    
        
        
        
        original_filename = item['doc']
        filename = form.filename.data
        audio_data, sampling_rate = librosa.load('uploads/'+original_filename)
        dict['tempo']=int(librosa.beat.tempo(audio_data,sampling_rate)[0])

        # Evite les erreurs lors de la 1ere connexion
        if filename == ''  :
            return render_template('mix.html',**dict)
        
        # On recupere les donnée du formulaire
        genre = form.genre.data
        speed = form.speed.data
        bass = form.bass.data
        tone = form.tone.data
        sampling_rate = form.sampling_rate.data
        drum_funk = form.drum_funk.data
        drum_blues = form.drum_blues.data
        inst_debut=form.inst_debut.data
        inst_fin=form.inst_fin.data
        insert_time=form.insert_time.data
        sample_id=form.sample_id.data

        # Si les champs du formulaire sont vides, il faut quand même donner des valeurs acceptables
        if inst_debut == '':inst_debut='0'
        if inst_fin == '' : inst_fin = str(-1/sampling_rate)
        
        print(drum_blues)
        print(drum_funk)
        
        cur = mysql.connection.cursor()
        result=cur.execute("SELECT doc FROM sample WHERE id=%s ",[id])
        nom_file=cur.fetchone()
        cur.close()

        # Changements sur le fichier audio

        # Partie obsolète à cause du module librosa qui ne fonctionne plus
        
        data_final=cut(audio_data,int(float(inst_debut)*sampling_rate), int(float(inst_fin)*sampling_rate))
        if drum_funk == "activate" : 
            data_final = percu(data_final,son_percu="./uploads/Batterie_funk_1.wav")
        if drum_blues == "activate":
            data_final = percu(data_final,son_percu="./uploads/Batterie_blues_1.wav")
        if insert_time != "":
            data_final = sample_unique(data_final,"./uploads"+nom_file['doc'],insert_time)
        if speed != 1:
            data_final = librosa.effects.time_stretch(data_final, speed)
        if tone != 0:
            data_final = librosa.effects.pitch_shift(data_final, sampling_rate, tone)
        if bass != 1:
            data_final= change_bass(data_final,bass)

        sf.write('downloads/'+filename, data_final, sampling_rate)
        

        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO Musique(titre, artiste, doc) VALUES(%s, %s, %s)", (item['titre'], item['artiste'], filename))
        mysql.connection.commit()
        cur.close()


        # Rajouter les validators dans les formulaires
        flash('Changements appliqués à la musique', 'success')
        return redirect(url_for('appliquer_changements', id=id))
    return render_template('mix.html', **dict)
Пример #28
0
        print('Вводите числа через "Enter" без пробелов, чтобы закончить введите "!"')
        while x != '!':
            x = input()
            if x != '!':
                a.append(int(x))
print('Ответ программы с визуализацией:')
while len(a) > 0:
    for i in range(len(a)):
        if len(a) > 1 and int(a[0]) < int(a[1]):
            ft.sa(a)
            print('exec sa')
            print("   a -", *a)
            print("   b -", *b)
            fout.write('sa ')
        ft2.ra(a)
        a = ft5.cut(a)
        print('exec ra')
        print("   a -", *a)
        print("   b -", *b)
        fout.write('ra ')
    b = ft1.pb(a, b)
    a = ft5.cut(a)
    print('exec pb')
    print("   a -", *a)
    print("   b -", *b)
    fout.write('pb ')
for i in range(len(b)):
    a = ft1.pa(b, a)
    b = ft5.cut(b)
    print('exec pa')
    print("   a -", *a)
Пример #29
0
original = Image.open('cropped/{:s}.png'.format(dataset))
enhanced = Image.open('enhanced/{:s}.png'.format(dataset))
if 'test' in argv:
    with open('offsets.txt') as od:
        for line in od:
            fields = line.split()
            f = fields[2]
            if f == dataset:
                x0 = int(fields[3])
                y0 = int(fields[4])
    x = int(input('X: ')) - x0
    y = int(input('Y: ')) - y0
    zone = (x - r, y - r, x + r, y + r)
    print(f'Extracting a {2 * r} square at {x}, {y}')
    square = original.crop(zone)
    cut(square, d, circle(d, margin, opacity=200), 'test.png')
    quit()
if postprocess:
    print('Post-processing for manuscript figures', dataset)
    thresholded = Image.open('thresholded/{:s}.png'.format(dataset))
    automaton = Image.open('automaton/{:s}.png'.format(dataset))
    w, h = thresholded.size
    factor = ow / w
    sr = radius(dataset, factor) // 2
    sd = 2 * sr
    smask = circle(sd)
for treeID in trees:
    pos, label = trees[treeID]
    x, y = pos
    zone = (x - r, y - r, x + r, y + r)
    square = original.crop(zone)
Пример #30
0
def build(argv):

    doCatalogue = True
    doQuick = False
    doPublish = False
    try:
        opts, args = getopt.getopt(argv,"hcqp",[])
    except getopt.GetoptError:
        print 'build.py -h -c -q -p'
        print ''
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'Usage: -h -c -q -p'
            print ''
            print '  -c   Skip catalogue'
            print '  -p   Publish: auto commit and push to git'
            print '  -q   Quick build - skip assemblies, guide and catalogue'
            sys.exit()
        if opt in ("-c"):
            doCatalogue = False
        if opt in ("-q"):
            doQuick = True
            doCatalogue = False
        if opt in ("-p"):
            doPublish = True

    print("Build")
    print("-----")

    outfile = 'hardware.json'
    oldfile = 'backup.json'

    print("Backup current json...")
    oldjso = None
    if os.path.isfile(outfile) and not os.path.isfile(oldfile):
        os.rename(outfile, oldfile)

    errorlevel = 0

    errorlevel += parse_machines()

    if errorlevel == 0:
        errorlevel += vitamins()
    if errorlevel == 0:
        errorlevel += cut()
    if errorlevel == 0:
        errorlevel += printed()
    if errorlevel == 0 and not doQuick:
        errorlevel += assemblies()
    if errorlevel == 0:
        errorlevel += machines()

    if errorlevel == 0 and not doQuick:
        errorlevel += guides()

    if doCatalogue and not doQuick:
        catalogue()

    if errorlevel == 0 and doPublish > 0:
        publish()


    # if everything is ok then delete backup - no longer required
    if errorlevel == 0:
        os.remove(oldfile)

    try:
        if sys.platform == "darwin":
            check_output(['osascript','-e','display notification "Build Complete" with title "Build Process"'])
    except:
        print("Exception running osascript")

    print("")
    print("==============")
    print("Build Complete")

    return errorlevel
Пример #31
0
def build(argv):

    doCatalogue = True
    doQuick = False
    try:
        opts, args = getopt.getopt(argv, "hcq", [])
    except getopt.GetoptError:
        print('build.py -h -c -q')
        print('')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('Usage: -h -c -q')
            print('')
            print('  -c   Skip catalogue')
            print('  -q   Quick build - skip assemblies, guide and catalogue')
            sys.exit()
        if opt in ("-c"):
            doCatalogue = False
        if opt in ("-q"):
            doQuick = True
            doCatalogue = False

    print("Build")
    print("-----")

    print("Backup current json...")
    oldjso = None
    if os.path.isfile(config.paths['json']) and not os.path.isfile(
            config.paths['jsonbackup']):
        os.rename(config.paths['json'], config.paths['jsonbackup'])

    errorlevel = 0

    errorlevel += parse_machines()

    if errorlevel == 0:
        errorlevel += vitamins()
    if errorlevel == 0:
        errorlevel += cut()
    if errorlevel == 0:
        errorlevel += printed()
    if errorlevel == 0 and not doQuick:
        errorlevel += assemblies()
    if errorlevel == 0:
        errorlevel += machines()

    if errorlevel == 0 and not doQuick:
        errorlevel += guides()

    if doCatalogue and not doQuick:
        catalogue()

    # if everything is ok then delete backup - no longer required
    if errorlevel == 0 and os.path.isfile(config.paths['jsonbackup']):
        os.remove(config.paths['jsonbackup'])

    try:
        if sys.platform == "darwin":
            check_output([
                'osascript', '-e',
                'display notification "Build Complete" with title "Build Process"'
            ])
    except:
        print("Exception running osascript")

    print("")
    print("==============")
    print("Build Complete")

    if errorlevel > 0:
        print("Error: " + str(errorlevel))

    return errorlevel
Пример #32
0
    def cutBtnHandler(self):
        fig = cut.cut(self.lines, self.cutter)

        for i, v in enumerate(fig):
            self.drawLine(fig[i], fig[(i + 1) % len(fig)],
                          self.CUTTED_LINE_COLOR)
Пример #33
0
            '4) Change the audio into mono and apply a different audio codec'
        ]),
]

exercice = inquirer.prompt(menu)['menu']

if '1)' in exercice:
    print(
        'Define the time the trimmed video will start as mm:ss knowing that the maximun is 10:25'
    )
    while 1:
        time = str(input())
        a = time.split(':')
        if int(a[0]) < 11 and int(a[1]) < 61:
            print('\nTime: ', time)
            cut(time)
            break
        else:
            print('Invalid option, choose another time')

elif '2)' in exercice:
    histogram()

elif '3)' in exercice:
    print(
        'Define the width and height as (360x240) or the resolution as (720p)')
    while 1:
        size = str(input())
        if 'p' in size or 'x' in size:
            print('\nSize: ', size)
            resize(size)
Пример #34
0
from cut import cut
png = cut()