def crop_and_process(self, img):
		crop = Crop()
		final_img = crop.run(img)
		#plt.imshow(final_img)
		final_img = cv2.cvtColor(final_img, cv2.COLOR_BGR2GRAY)
		#plt.imshow(final_img)
		return self.detector.run(final_img)
Exemple #2
0
    def update(self, external_info):
        """
        Update the soil water properties by solving the water fluxes.

        # Arguments
            external_info (dict): requires information on potential transpiration and evaporation

        # Returns
            None:

        """
        self.daily_water_balance(external_info['petcrop'], external_info['petsoil'])
        external_info['cropstress'] = self.waterstresses.crop   # info on water stress for Crop
        Crop.update(self, external_info)
Exemple #3
0
    def __init__(self, fname_in):
        """
        Create and initialize the SoilWater object.

        # Arguments
            fname_in (str): path and filename of the model initialization file

        """
        Crop.__init__(self, fname_in)   # initialize the parent class first

        d = self.ini
        self.numintervals = d['numintervals']  # number of intervals for integration within a day
        self.rootdepth = d['rootdepth']  # rooting depth (m)
        self.has_watertable = d['has_watertable']     # has a water table / groundwater?
        self.numlayers = d['numlayers']  # the number of soil layers
        self.layers = [SoilLayer() for _ in range(self.numlayers)]  # create the soil layers

        # read in the properties for each soil layer. If there is a water table, the last soil
        #    layer is assumed to border the water table surface
        dl = d['layers']
        for i, layer in enumerate(self.layers):
            layer.thick = dl[i]['thick']  # thickness of each soil layer (m)
            layer.vwc = dl[i]['vwc']  # vol. water content in m3/m3
            layer.wc = layer.vwc * layer.thick * 1000  # convert from m3/m3 to mm water
            tex = dl[i]['texture']  # clay, sand, and OM percentages (%)
            layer.texture = Texture(tex['clay'], tex['sand'], tex['om'])

        # initialize the soil layers (those that do not change with water content)
        for i in range(self.numlayers):
            prevlayer = self.layers[i - 1] if i > 0 else None
            nextlayer = self.layers[i + 1] if i < self.numlayers - 1 else None
            self.layers[i].initialize_layer(prevlayer, nextlayer)

        # internal use: speedier calculations: proxy to store intermediate water flux values
        #    fluxes within a sub-interval daily time step
        self.__pf = [{f: 0.0 for f in SoilLayer.flux_fields} for _ in range(self.numlayers)]

        # cumulative fluxes at the end of a daily time step
        self.cf = [{f: 0.0 for f in SoilLayer.flux_fields} for _ in range(self.numlayers)]
        # root zone water characteristics:
        self.rootwater = RootWater()
        self.update_rootwater()  # amount of water in the root zone (mm and m3/m3)
        # reduction to evaporation and transpiration due to water stress
        self.waterstresses = self.reduce_et()
        self.netrain = 0.0  # net rainfall (mm/day)
        self.aet = AET(0.0, 0.0)  # actual water loss by ET (mm/day)
Exemple #4
0
    def __init__(self,
                 data_dir,
                 split_path,
                 config,
                 phase='train',
                 split_comber=None,
                 start=0,
                 end=0,
                 r_rand=None,
                 with_augmented=False):
        assert (phase == 'train' or phase == 'val' or phase == 'test')
        self.phase = phase
        self.max_stride = config['max_stride']
        self.stride = config['stride']
        sizelim = config['sizelim'] / config['reso']
        sizelim2 = config['sizelim2'] / config['reso']
        sizelim3 = config['sizelim3'] / config['reso']
        self.blacklist = config['blacklist']
        self.isScale = config['aug_scale']
        self.r_rand = config['r_rand_crop'] if r_rand is None else r_rand
        self.augtype = config['augtype']
        self.pad_value = config['pad_value']
        self.split_comber = split_comber
        idcs = split_path
        self.filenames, self.sample_bboxes = get_filenames_and_labels(
            idcs, start, end, data_dir, with_augmented)

        if self.phase != 'test':
            self.bboxes = []

            for i, l in enumerate(self.sample_bboxes):
                if len(l) > 0:
                    for t in l:
                        if t[3] > sizelim:
                            self.bboxes += [[np.concatenate([[i], t])]]
                        if t[3] > sizelim2:
                            self.bboxes += [[np.concatenate([[i], t])]] * 2
                        if t[3] > sizelim3:
                            self.bboxes += [[np.concatenate([[i], t])]] * 4
            self.bboxes = np.concatenate(self.bboxes, axis=0)

        self.crop = Crop(config)
        self.label_mapping = LabelMapping(config, self.phase)
Exemple #5
0
def predict(model):
    c = Crop()
    eye = Screen()
    zumi = Zumi()
    camera = Camera(64, 64)
    personality = Personality(zumi, eye)

    cnt = 0
    prev_label = -1
    cnt_none_crop = 0
    try:
        while True:
            zumi.reset_drive()
            img = camera.run()
            crop_img = c.crop(img)
            if crop_img is None:

                if cnt_none_crop == 0:
                    personality.look_around_open01()
                elif cnt_none_crop == 1:
                    personality.look_around_open02()
                elif cnt_none_crop == 2:
                    personality.look_around_open03()
                elif cnt_none_crop == 3:
                    personality.look_around_open04()

                prev_label = -1
                print(cnt, prev_label, cnt_none_crop)
                cnt_none_crop += 1
                cnt_none_crop %= 4

                continue
            else:
                cnt_none_crop = 0

            x = Image.fromarray(crop_img)
            x = np.expand_dims(x, axis=0)
            preds = model.predict_classes(x)
            print(landmark[preds[0]])

            if prev_label == preds[0]:
                cnt += 1
                if cnt > 2:
                    print(eye.EYE_IMAGE_FOLDER_PATH + "sad1.ppm")
                    print("reaction!!!!")
                    eye.draw_image(
                        eye.path_to_image(LAND_PATH + landmark[preds[0]] +
                                          ".jpg"))
                    time.sleep(2)
                    if landmark[preds[0]] == 'eiffel':
                        zumi.turn_right(90)
                    elif landmark[preds[0]] == 'nyc':
                        zumi.turn_right(45)
                    elif landmark[preds[0]] == 'seattle':
                        zumi.turn_left(45)
                    elif landmark[preds[0]] == 'china':
                        zumi.turn_left(90)

                    time.sleep(.5)
                    zumi.forward(10, duration)
                    time.sleep(.5)
                    personality.celebrate()
                    time.sleep(.5)
                    zumi.reverse(10, duration)
                    time.sleep(.5)

                    if landmark[preds[0]] == 'eiffel':
                        zumi.turn_left(90)
                    elif landmark[preds[0]] == 'nyc':
                        zumi.turn_left(45)
                    elif landmark[preds[0]] == 'seattle':
                        zumi.turn_right(45)
                    elif landmark[preds[0]] == 'china':
                        zumi.turn_right(90)

                    cnt = 0
                else:
                    personality.reading(
                        eye.path_to_image(READ_PATH + "reading_" + str(cnt) +
                                          ".PPM"))
            else:
                cnt = 0
                prev_label = preds[0]

    except KeyboardInterrupt:
        camera.shutdown()
        eye.draw_text("")
        zumi.stop()
        print("\nExiting...")
    except:
        camera.shutdown()
        eye.draw_text("")
        zumi.stop()
        print("\nExiting...")
Exemple #6
0
import cv2
from crop import Crop
import numpy as np

capture = cv2.VideoCapture(0)
crop = Crop()

while True:
    ok, frame = capture.read()
    w, h = frame.shape[1::-1]
    frame = cv2.resize(frame, (int(w * .5), int(h * .5)))
    crop.findColorRange(frame)
    crop.removeBackground()
    crop.trackObject()
    crop.showImage(delay=1)

cv2.destroyAllWindows()
capture.release()
Exemple #7
0
from matplotlib import pyplot as plt
from crop import Crop
from colour_picker import ColourPicker
import grab_cut
import k_means

img = cv2.imread("D:\Python\Lichen\images\lichen2.jpg")

img = cv2.resize(img, None, fx=0.1, fy=0.1, interpolation=cv2.INTER_CUBIC)

cv2.namedWindow('Lichen Image')

clonedImage = img.copy()

# Use a copy so roi can be drawn then thrown away
cropWindow = Crop(clonedImage)

roi = cv2.setMouseCallback('Lichen Image', cropWindow.crop)

while True:
    # display the image and wait for a keypress
    cv2.imshow("Lichen Image", cropWindow.imageToCrop)
    key = cv2.waitKey(1) & 0xFF

    # if the 'r' key is pressed, reset the cropping region
    if key == ord("r"):
        img = clonedImage.copy()

    # if the 'c' key is pressed, break from the loop
    elif key == ord("c"):
        break
Exemple #8
0
    den_outfile = os.path.join(den_outpath, filename)

    img = cv2.imread(infile, 0)

    print('start getting circle')

    img, height, width, allCenter, allRadius = GetCircle(img)

    print('start cutting img into small pieces')

    all_img, num = GetSquare(img, height, width, allCenter, allRadius)

    cv2.imwrite(outfile, all_img)
    padding = 16

    net_inpath, size = Crop(all_img, num, infile, crop_outpath, padding)

    print('piece len:', size)

    print('start referencing the small pieces')

    out = []

    for filename in os.listdir(net_inpath):

        imgname = os.path.join(net_inpath, filename)

        img = cv2.imread(imgname, 1)

        img = img_transform(img)
        with torch.no_grad():
Exemple #9
0
def predict(model,Reroute=False):
    c = Crop()
    eye = Screen()
    zumi = Zumi()
    camera = Camera(64, 64)
    personality = Personality(zumi, eye)

    cnt = 0
    prev_label = -1
    cnt_none_crop = 0
    try:
        while True:
            img = camera.run()
            crop_img = c.crop(img)
            if crop_img is None:

                if cnt_none_crop == 0:
                    personality.look_around_open01()
                elif cnt_none_crop == 1:
                    personality.look_around_open02()
                elif cnt_none_crop == 2:
                    personality.look_around_open03()
                elif cnt_none_crop == 3:
                    personality.look_around_open04()

                prev_label = -1
                print(cnt, prev_label, cnt_none_crop)
                cnt_none_crop += 1
                cnt_none_crop %= 4

                continue
            else:
                cnt_none_crop = 0

            x = Image.fromarray(crop_img)
            x = np.expand_dims(x, axis=0)
            preds = model.predict_classes(x)
            print(landmark[preds[0]])

            if prev_label == preds[0]:
                cnt += 1
                if cnt > 2:
                    print(eye.EYE_IMAGE_FOLDER_PATH + "sad1.ppm")
                    print("reaction!!!!")
                    eye.draw_image(eye.path_to_image(LAND_PATH + landmark[preds[0]] + ".jpg"))
                    time.sleep(2)
                    route = Route_new()
                    if Reroute:
                        print("go with rerouting")
                        if landmark[preds[0]] == 'eiffel':
                            route.driving(route.start_node, route.paris)
                        elif landmark[preds[0]] == 'nyc':
                            route.driving(route.start_node, route.NY)
                        elif landmark[preds[0]] == 'seattle':
                            route.driving(route.start_node, route.seattle)
                        elif landmark[preds[0]] == 'china':
                            route.driving(route.start_node, route.china)
                        else:
                            route.driving(route.start_node, route.bigben)
                        zumi.stop()
                        personality.celebrate()
                        time.sleep(.5)
                    else:
                        print("no reroute")
                        if landmark[preds[0]] == 'eiffel':
                            route.driving_without_reroute(route.start_node, route.paris)
                            route.park_right()
                        elif landmark[preds[0]] == 'nyc':
                            route.driving_without_reroute(route.start_node, route.NY)
                            route.park_right()
                        elif landmark[preds[0]] == 'seattle':
                            route.driving_without_reroute(route.start_node, route.seattle)
                            route.park_left()
                        elif landmark[preds[0]] == 'china':
                            route.driving_without_reroute(route.start_node, route.china)
                            route.park_left()
                        else:
                            route.driving_without_reroute(route.start_node, route.bigben)
                            route.park_right()
                        zumi.stop()
                        personality.celebrate()
                        time.sleep(.5)

                    cnt = 0
                else:
                    personality.reading(eye.path_to_image(READ_PATH + "reading_" + str(cnt) + ".PPM"))
            else:
                cnt = 0
                prev_label = preds[0]

    except KeyboardInterrupt:
        camera.shutdown()
        eye.draw_text("")
        zumi.stop()
        print("\nExiting...")
    except:
        camera.shutdown()
        eye.draw_text("")
        zumi.stop()
        print("\nExiting...")
Exemple #10
0
def main():
    global args, best_prec1
    args = parser.parse_args()
    print(args)

    traindir = os.path.join(args.data, 'train')
    valdir = os.path.join(args.data, 'val')
    # num_classes = len([name for name in os.listdir(traindir)
    #                    if not os.path.isfile(os.path.join(traindir, name))])
    # print('=> found {} classes'.format(num_classes))

    # create model
    model = Net()
    # print model

    # optionally resume from a checkpoint
    if args.resume:
        if os.path.isfile(args.resume):
            print("=> loading checkpoint '{}'".format(args.resume))
            checkpoint = torch.load(args.resume, map_location='cpu')
            args.start_epoch = checkpoint['epoch']
            best_prec1 = checkpoint['best_prec1']
            # model.load_state_dict(checkpoint['state_dict'])
            state_dict = {str.replace(
                k, 'module.', ''): v for k, v in checkpoint['state_dict'].items()}
            model.load_state_dict(state_dict)
            print("=> loaded checkpoint '{}' (epoch {})"
                  .format(args.resume, checkpoint['epoch']))
        else:
            print("=> no checkpoint found at '{}'".format(args.resume))

    # Data loading code
    normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
                                     std=[0.5, 0.5, 0.5])

    dataset_train = datasets.ImageFolder(
        traindir,
        transform=transforms.Compose([
            Crop((0, 0), (720, 720)),
            transforms.Resize(256),
            # transforms.RandomResizedCrop(224),
            # transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            normalize,
        ]),
    )
    train_loader = torch.utils.data.DataLoader(
        dataset_train,
        batch_size=args.batch_size, shuffle=True,
        num_workers=args.workers, pin_memory=True)

    val_loader = torch.utils.data.DataLoader(
        datasets.ImageFolder(
            valdir,
            transform=transforms.Compose([
                Crop((0, 0), (720, 720)),
                transforms.Resize(256),
                # transforms.CenterCrop(224),
                transforms.ToTensor(),
                normalize,
            ]),
        ),
        batch_size=args.batch_size, shuffle=False,
        num_workers=args.workers, pin_memory=True)

    # define loss function (criterion) and optimizer
    criterion = nn.BCELoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)
    # optimizer = torch.optim.SGD(model.parameters(), args.lr,
    #                             momentum=0.9,
    #                             weight_decay=1e-4)

    if args.evaluate:
        validate(val_loader, model, criterion)
        return

    for epoch in range(args.start_epoch, args.epochs):
        adjust_learning_rate(optimizer, epoch)

        # train for one epoch
        train(train_loader, model, criterion, optimizer, epoch)

        # evaluate on validation set
        prec1 = validate(val_loader, model, criterion)

        # remember best prec@1 and save checkpoint
        is_best = prec1 > best_prec1
        best_prec1 = max(prec1, best_prec1)
        save_checkpoint({
            'epoch': epoch + 1,
            'state_dict': model.state_dict(),
            'best_prec1': best_prec1,
        }, is_best)