Beispiel #1
0
def main(mode="random", iter_num=20, k=5):
    """average time to 1 pair = (2 / k^2) sec"""

    if mode == "random":
        from random import uniform
        from time import time

        img1 = cv2.imread("comp1.tif")
        img1 = tools.resize(img1, k)
        cont = []
        for i in range(iter_num):

            dx = dy = 0
            dr = 0

            shift = (uniform(-dx, dx), uniform(-dy, dy))
            rot = (uniform(-dr, dr))
            img2 = tools.get_img(img1, shift, rot)

            solver = Solution(img1, img2, 100)

            print("RIGHT", rot, shift)

            start = time()
            solver.estimate()
            shift1 = [0, 0]
            rot1, shift1[0], shift1[1] = solver.rotXY
            if rot1 != False:
                print("EST", rot1, shift1)
                print("rotXY", solver.rotXY)
                delta = [
                    abs(rot - rot1),
                    abs(shift[0] - shift1[0]),
                    abs(shift[1] - shift1[1])
                ]
                print(f"FALLIBILITY = {delta}")
            else:
                print("NOT")

            cont.append(time() - start)
            print("___")
        print(
            f"MAX = {max(cont)}, MIN = {min(cont)}, AVERAGE = {sum(cont) / iter_num} SECONDS"
        )

    elif mode == "compare":
        name1, name2 = f"/MESSIDOR/1pp.tif", f"/MESSIDOR/20051216_43913_0200_PP.tif"
        img1 = (cv2.imread(name1))
        img2 = (cv2.imread(name2))
        #img2 = tools.rotAlignment(img2, 0)

        #tools.show(img1)
        #tools.show(img2)
        img1 = segm.extract_bv(tools.resize(img1, k))
        img2 = segm.extract_bv(tools.resize(img2, k))
        solver = Solution(img1, img2)
        print(solver.estimate())
        return 0
Beispiel #2
0
def tell(path):
    # print(model.to_json())

    # import h5py as h5
    # h = h5.File("./output/lenet.hdf5","r")
    # print(h.keys())

    # image = cv2.imread("./smiles/positives/positives7/24.jpg")
    image = cv2.imread(path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = tools.resize(image, 28)

    cv2.imwrite("./smiles/mine/mine_proc.jpg", image)
    image = img_to_array(image)
    data = []
    data.append(image)
    data = np.array(data, dtype="float") / 255.0
    # print(np.info(data))
    if not image.any():
        print("No image input!")
    else:
        model = load_model('./output/lenet.hdf5')
        predict = model.predict(data)
        print(predict)
        if predict.argmax(axis=1)[0]:  # positive = 1, negative = 0
            print("Positive!")
        else:
            print("Negative!")
Beispiel #3
0
    def _generateCover(self, inFile, outFile, format, max_width, max_height):
        from PIL import Image

        try:
            # Open the image
            cover = Image.open(inFile)
            width = cover.size[0]
            height = cover.size[1]
            newWidth, newHeight = tools.resize(width, height, max_width,
                                               max_height)

            cover = cover.resize((newWidth, newHeight), Image.ANTIALIAS)
            cover.save(outFile, format)
        except Exception:
            # This message will probably be displayed for the thumbnail and the big cover.
            logger.error(
                '[%s] An error occurred while generating the cover for "%s"\n\n%s'
                % (MOD_NAME, inFile, traceback.format_exc()))
            # Remove corrupted file.
            tools.remove(outFile)
Beispiel #4
0
# 命令行参数
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True)
ap.add_argument("-m", "--model", required=True)
args = vars(ap.parse_args())

# 数据和标签列表
data = []
labels = []
epoch = 10  # default: 15

# 遍历每一张样本图片
for imagePath in sorted(list(tools.list_images(args["dataset"]))):
    image = cv2.imread(imagePath)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = tools.resize(image, width=28)
    image = img_to_array(image)
    data.append(image)

    # 样本图片路径smiles/positives/positives7/13229.jpg
    label = imagePath.split(os.path.sep)[-3]
    label = "smiling" if label == "positives" else "not_smiling"
    labels.append(label)

# 缩放到[0,1]
# print(data[0][0])
data = np.array(data, dtype="float") / 255.0
# print(data[0][0])
# print(np.info(data))
labels = np.array(labels)
    klick = pygame.mixer.Sound("klick.wav")
    gong = pygame.mixer.Sound("gong.wav")
    error = pygame.mixer.Sound("error.wav")

    dinfo = pygame.display.Info()
    video_flags = OPENGL | HWSURFACE | DOUBLEBUF | FULLSCREEN

    #ein paar variablen zu den seitenverhaeltnissen:
    SCREEN_RATIO = float(dinfo.current_w) / float(dinfo.current_h)  #16:9
    GITTER_RATIO = float(gitter.GITTER_W) / float(gitter.GITTER_H)

    FIELD_W_RATIO = (GITTER_RATIO * float(dinfo.current_h)) / float(
        dinfo.current_w)

    pygame.display.set_mode((dinfo.current_w, dinfo.current_h), video_flags)
    tools.resize((dinfo.current_w, dinfo.current_h))
    tools.GlInit()
    tools.clearScreen()

    eManager = eventmanager.eventmanager()

    mausimaus = maus.maus()

    git = gitter.gitter((dinfo.current_w * FIELD_W_RATIO, dinfo.current_h),
                        eManager, mausimaus, (klick, gong, error))

    sidebar = hud.hud(
        (dinfo.current_w * FIELD_W_RATIO + 2, 2, dinfo.current_w -
         dinfo.current_w * FIELD_W_RATIO - 4, dinfo.current_h - 4), mausimaus,
        font)
Beispiel #6
0
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-c", "--cascade", required=True)
ap.add_argument("-m", "--model", required=True)
args = vars(ap.parse_args())

detector = cv2.CascadeClassifier(args["cascade"])
model = load_model(args["model"])

camera = cv2.VideoCapture(0)

while True:
    (grabbed, frame) = camera.read()

    frame = tools.resize(frame, width=900)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    frameNew = frame.copy()

    # 在灰度图上检测人脸,得到所有矩形。
    rects = detector.detectMultiScale(gray,
                                      scaleFactor=1.1,
                                      minNeighbors=5,
                                      minSize=(30, 30),
                                      flags=cv2.CASCADE_SCALE_IMAGE)

    # 循环每一个检测出人脸的矩形区域
    for (fX, fY, fW, fH) in rects:
        # 抽取ROI区域,缩放为28*28
        roi = gray[fY:fY + fH, fX:fX + fW]
        roi = cv2.resize(roi, (28, 28))
    multinom_bkg = list(np.random.multinomial(1, prob_bkg))
    draw_bkg = multinom_bkg.index(1)
    bkg_name = background_list[draw_bkg]

    multinom_card = list((np.random.multinomial(1, prob_card)))
    draw_card = multinom_card.index(1)
    card_name = card_list[draw_card]

    bkg = PIL.Image.open(path + "/Backgrounds/" + bkg_name)
    card = Image.open(path + "/Cards/" + card_name)
    card = card.convert('RGBA')

    # Give random size on card image
    ratio = np.random.normal(2.2, 0.1)
    print("Card ratio: " + str(round(ratio, 2)))
    card = tools.resize(card, ratio)

    # Set a paste position of card around the middle of the background image.
    # Top left corner position is starting coords (0,0), not middle.
    x_val = bkg.size[0] / 2 - card.size[0] / 2
    y_val = bkg.size[1] / 2 - card.size[1] / 2

    x_offset = int(np.random.normal(x_val, x_val / 5.5))
    y_offset = int(np.random.normal(y_val, y_val / 5.5))

    # Copy images
    back_im = bkg.copy()
    card_im = card.copy()

    # Set variables to be used in mutation
    w, h = card_im.size
Beispiel #8
0

checkpoint = torch.load('../fast-depth/mobilenet-nnconv5dw-skipadd.pth.tar', 
        map_location=torch.device('cpu'))

torch_model = checkpoint['model']

import cv2
import tools

cap = cv2.VideoCapture('/home/sebastian/Desktop/SLAM-CPP/home.MOV')
ret, frame = cap.read()

while False:
    #frame = cv2.resize(frame, (224, 224))
    frame = tools.resize(frame)
    cv2.imshow('frame', frame)
    
    model_in = np.expand_dims(np.array(frame, dtype=np.float32)/255., 0)

    tf_prediction = model.predict(model_in)
    tf_prediction = np.squeeze(tf_prediction)
    tf_prediction = tools.toShow(tf_prediction)

    model_in = np.moveaxis(model_in, -1, 1)
    torch_model_in = torch.tensor(model_in).float()
    torch_prediction = torch_model(torch_model_in)
    torch_prediction = torch_prediction.detach().numpy().squeeze()
    torch_prediction = tools.toShow(torch_prediction)
    cv2.imshow('tf_prediction', tf_prediction)
    cv2.imshow('torch_prediction', torch_prediction)