Detect features in image
12720
function() {
            if (!this._image instanceof IMSoftcrop.Image || !this._image.ready) {
                return;
            }

            var _this = this,
                imageData = this.getImageData();

            this._waitForWorkers++;

            if (window.Worker) {
                // If workers are available, thread detection of faces
                var detectWorker = new Worker(this._detectWorkerUrl);

                detectWorker.postMessage([
                    'details',
                    imageData,
                    this._image.w,
                    this._image.h,
                    this._detectThreshold
                ]);

                detectWorker.onmessage = function(e) {
                    _this.addDetectedDetails(e.data);
                    _this._waitForWorkers--;
                    _this.autocropImages();
                };
            }
            else {
                // Fallback to non threaded
                var data = tracking.Fast.findCorners(
                    tracking.Image.grayscale(
                        imageData.data,
                        this._image.w,
                        this._image.h
                    ),
                    this._image.w,
                    this._image.h,
                    this._detectThreshold
                );

                this.addDetectedDetails(data);
                this._waitForWorkers--;
                this.autocropImages();
            }
        }
330286
def detect_faces(self, img) -> list:
        
        if img is None or not hasattr(img, "shape"):
            raise InvalidImage("Image not valid.")

        height, width, _ = img.shape
        stage_status = StageStatus(width=width, height=height)

        m = 12 / self.__min_face_size
        min_layer = np.amin([height, width]) * m

        scales = self.__compute_scale_pyramid(m, min_layer)

        stages = [self.__stage1, self.__stage2, self.__stage3]
        result = [scales, stage_status]

        # We pipe here each of the stages
        for stage in stages:
            result = stage(img, result[0], result[1])

        [total_boxes, points] = result

        bounding_boxes = []

        for bounding_box, keypoints in zip(total_boxes, points.T):

            bounding_boxes.append({
                    'box': [int(bounding_box[0]), int(bounding_box[1]),
                            int(bounding_box[2]-bounding_box[0]), int(bounding_box[3]-bounding_box[1])],
                    'confidence': bounding_box[-1],
                    'keypoints': {
                        'left_eye': (int(keypoints[0]), int(keypoints[5])),
                        'right_eye': (int(keypoints[1]), int(keypoints[6])),
                        'nose': (int(keypoints[2]), int(keypoints[7])),
                        'mouth_left': (int(keypoints[3]), int(keypoints[8])),
                        'mouth_right': (int(keypoints[4]), int(keypoints[9])),
                    }
                }
            )

        return bounding_boxes
904406
private void extractImageFeatures(final ProgressMonitor progressMonitor, final int progress,
									  T image,
									  List<TupleDesc> descs, List<Point2D_F64> locs) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				progressMonitor.setNote("Detecting");
			}
		});
		detector.detect(image);
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				progressMonitor.setProgress(progress + 1);
				progressMonitor.setNote("Describing");
			}
		});
		describe.setImage(image);
		orientation.setImage(image);

		// See if the detector can detect the feature's scale
		if (detector.hasScale()) {
			for (int i = 0; i < detector.getNumberOfFeatures(); i++) {
				double yaw = 0;

				Point2D_F64 pt = detector.getLocation(i);
				double radius = detector.getRadius(i);
				if (describe.requiresOrientation()) {
					orientation.setObjectRadius(radius);
					yaw = orientation.compute(pt.x, pt.y);
				}

				TupleDesc d = describe.createDescription();
				if ( describe.process(pt.x, pt.y, yaw, radius, d) ) {
					descs.add(d);
					locs.add(pt.copy());
				}
			}
		} else {
			// just set the radius to one in this case
			orientation.setObjectRadius(1);
			for (int i = 0; i < detector.getNumberOfFeatures(); i++) {
				double yaw = 0;

				Point2D_F64 pt = detector.getLocation(i);
				if (describe.requiresOrientation()) {
					yaw = orientation.compute(pt.x, pt.y);
				}

				TupleDesc d = describe.createDescription();
				if (describe.process(pt.x, pt.y, yaw, 1, d)) {
					descs.add(d);
					locs.add(pt.copy());
				}
			}
		}
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				progressMonitor.setProgress(progress + 2);
			}
		});
	}
333149
def multi_feat_match(template, image, options=None):
    
    h, w = image.shape[:2]
    scale = 1
    if options is not None and 'features' in options:
        heatmap = np.zeros((h, w), dtype=np.float64)
        for foptions in options['features']:
            f_hmap, _ = feature_match(template, image, foptions)
            heatmap += cv.resize(f_hmap, (w, h), interpolation=cv.INTER_AREA)
        heatmap /= len(options['features'])
    else:
        heatmap, scale = feature_match(template, image, options)
    return heatmap, scale
172180
def image_shape(img):
    ''''''
    if hasattr(img, 'shape'):
        return (img.shape[1], img.shape[0])
    return (img.width, img.height)
717074
def read_image(img_spec, bkground_thresh, ensure_num_dim=3):
    """"""

    img = load_image_from_disk(img_spec)

    if not np.issubdtype(img.dtype, np.floating):
        img = img.astype('float32')

    if ensure_num_dim == 3:
        img = check_image_is_3d(img)
    elif ensure_num_dim == 4:
        img = check_image_is_4d(img)

    return threshold_image(img, bkground_thresh)
674744
def find_image_position(origin='origin.png', query='query.png', outfile=None):
    '''
    
    '''
    img1 = cv2.imread(query, 0) # query image(small)
    img2 = cv2.imread(origin, 0) # train image(big)

    # Initiate SIFT detector
    sift = cv2.SIFT()

    # find the keypoints and descriptors with SIFT
    kp1, des1 = sift.detectAndCompute(img1,None)
    kp2, des2 = sift.detectAndCompute(img2,None)
    print len(kp1), len(kp2)

    FLANN_INDEX_KDTREE = 0
    index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
    search_params = dict(checks = 50)

    # flann
    flann = cv2.FlannBasedMatcher(index_params, search_params)
    matches = flann.knnMatch(des1, des2, k=2)

    # store all the good matches as per Lowe's ratio test.
    good = []
    for m,n in matches:
        if m.distance < 0.7*n.distance:
            good.append(m)
    print len(kp1), len(kp2), 'good cnt:', len(good)

    if len(good)*1.0/len(kp1) < 0.5:
    #if len(good)<MIN_MATCH_COUNT:
        print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
        return img2.shape, img1.shape, []

    queryPts = []
    trainPts = []
    for dm in good:
        queryPts.append(kp1[dm.queryIdx])
        trainPts.append(kp2[dm.trainIdx])

    img3 = cv2.drawKeypoints(img1, queryPts)
    cv2.imwrite('image/query.png', img3)

    img3 = cv2.drawKeypoints(img2, trainPts)
    point = _middlePoint(trainPts)
    print 'position in', point

    if outfile:
        edge = 10
        top_left = (point[0]-edge, point[1]-edge)
        bottom_right = (point[0]+edge, point[1]+edge)
        cv2.rectangle(img3, top_left, bottom_right, 255, 2)
        cv2.imwrite(outfile, img3)
    return img2.shape, img1.shape, [point]
1160069
def estimateFromImages(imgs1, imgs2=None, mn_mx=None, nbins=100):
    '''
    
    '''
    if imgs2 is None:
        imgs2 = [None] * len(imgs1)
    else:
        assert len(imgs1) == len(imgs2)

    y_vals = np.empty((len(imgs1), nbins))
    w_vals = np.zeros((len(imgs1), nbins))

    if mn_mx is None:
        print('estimating min and max image value')
        mn = 1e6
        mx = -1e6
        # get min and max image value checking all first images:
        for n, i1 in enumerate(imgs1):
            print('%s/%s' % (n + 1, len(imgs1)))
            i1 = imread(i1)
            mmn, mmx = _getMinMax(i1)
            mn = min(mn, mmn)
            mx = mx = max(mx, mmx)
        print('--> min(%s), max(%s)' % (mn, mx))
    else:
        mn, mx = mn_mx

    x = None
    print('get noise level function')
    for n, (i1, i2) in enumerate(zip(imgs1, imgs2)):
        print('%s/%s' % (n + 1, len(imgs1)))

        i1 = imread(i1)
        if i2 is not None:
            i2 = imread(i2)

        x, y, weights, _ = calcNLF(i1, i2, mn_mx_nbins=(mn, mx, nbins), x=x)
        y_vals[n] = y
        w_vals[n] = weights

    # filter empty places:
    filledPos = np.sum(w_vals, axis=0) != 0
    w_vals = w_vals[:, filledPos]
    y_vals = y_vals[:, filledPos]
    x = x[filledPos]

    y_avg = np.average(np.nan_to_num(y_vals),
                       weights=w_vals,
                       axis=0)
    w_vals = np.sum(w_vals, axis=0)
    w_vals /= w_vals.sum()

    fitParams, fn, i = _evaluate(x, y_avg, w_vals)
    return x, fn, y_avg, y_vals, w_vals, fitParams, i
225251
def vis_detection(im_orig, detections, class_names, thresh=0.7):
    """"""
    import matplotlib.pyplot as plt
    import random
    plt.imshow(im_orig)
    colors = [(random.random(), random.random(), random.random()) for _ in class_names]
    for [cls, conf, x1, y1, x2, y2] in detections:
        cls = int(cls)
        if cls > 0 and conf > thresh:
            rect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1,
                                 fill=False, edgecolor=colors[cls], linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(x1, y1 - 2, '{:s} {:.3f}'.format(class_names[cls], conf),
                           bbox=dict(facecolor=colors[cls], alpha=0.5), fontsize=12, color='white')
    plt.show()
384299
def imdecode(image_path):
    """"""
    import os
    assert os.path.exists(image_path), image_path + ' not found'
    im = cv2.imread(image_path)
    return im
1332152
def discriminator(self, imgs, y):
        
        yv = y
        y = tf.reshape(y, [-1, 1, 1, 10])
        with argscope(Conv2D, kernel_size=5, strides=1):
            l = (LinearWrap(imgs)
                 .ConcatWith(tf.tile(y, [1, 28, 28, 1]), 3)
                 .Conv2D('conv0', 11)
                 .tf.nn.leaky_relu()

                 .ConcatWith(tf.tile(y, [1, 14, 14, 1]), 3)
                 .Conv2D('conv1', 74)
                 .BatchNorm('bn1')
                 .tf.nn.leaky_relu()

                 .apply(batch_flatten)
                 .ConcatWith(yv, 1)
                 .FullyConnected('fc1', 1024, activation=tf.identity)
                 .BatchNorm('bn2')
                 .tf.nn.leaky_relu()

                 .ConcatWith(yv, 1)
                 .FullyConnected('fct', 1, activation=tf.identity)())
        return l
1218633
public int classify(T image) {
		if( numNeighbors == 0 )
			throw new IllegalArgumentException("Must specify number of neighbors!");

		// compute all the features inside the image
		describe.process(image);

		// find which word the feature matches and construct a frequency histogram
		featureToHistogram.reset();
		List<Desc> imageFeatures = describe.getDescriptions();
		for (int i = 0; i < imageFeatures.size(); i++) {
			Desc d = imageFeatures.get(i);
			featureToHistogram.addFeature(d);
		}
		featureToHistogram.process();
		temp.histogram = featureToHistogram.getHistogram();

		// Find the N most similar image histograms
		resultsNN.reset();
		search.findNearest(temp,-1,numNeighbors,resultsNN);

		// Find the most common scene among those neighbors
		Arrays.fill(scenes,0);
		for (int i = 0; i < resultsNN.size; i++) {
			NnData<HistogramScene> data = resultsNN.get(i);
			HistogramScene n = data.point;

//			scenes[n.type]++;
			scenes[n.type] += 1.0/(data.distance+0.005); // todo
//			scenes[n.type] += 1.0/(Math.sqrt(data.distance)+0.005); // todo
		}

		// pick the scene with the highest frequency
		int bestIndex = 0;
		double bestCount = 0;

		for (int i = 0; i < scenes.length; i++) {
			if( scenes[i] > bestCount ) {
				bestCount = scenes[i];
				bestIndex = i;
			}
		}

		return bestIndex;
	}
1205442
public void process( T image , GrayF32 intensity ) {
		int maxFeatures = (int)(maxFeaturesFraction*image.width*image.height);
		candidatesLow.reset();
		candidatesHigh.reset();
		this.image = image;

		if( stride != image.stride ) {
			stride = image.stride;
			offsets = DiscretizedCircle.imageOffsets(radius, image.stride);
		}
		helper.setImage(image,offsets);

		for (int y = radius; y < image.height-radius; y++) {
			int indexIntensity = intensity.startIndex + y*intensity.stride + radius;
			int index = image.startIndex + y*image.stride + radius;
			for (int x = radius; x < image.width-radius; x++, index++,indexIntensity++) {

				int result = helper.checkPixel(index);

				if( result < 0 ) {
					intensity.data[indexIntensity] = helper.scoreLower(index);
					candidatesLow.add(x,y);
				} else if( result > 0) {
					intensity.data[indexIntensity] = helper.scoreUpper(index);
					candidatesHigh.add(x,y);
				} else {
					intensity.data[indexIntensity] = 0;
				}
			}
			// check on a per row basis to reduce impact on performance
			if( candidatesLow.size + candidatesHigh.size >= maxFeatures )
				break;
		}
	}
1128154
def fitImg(self, img_rgb):
        '''
        
        '''
        H = self.pattern.findHomography(img_rgb)[0]
        H_inv = self.pattern.invertHomography(H)
        s = self.img_orig.shape
        warped = cv2.warpPerspective(img_rgb, H_inv, (s[1], s[0]))
        return warped
433610
public double[][] extractFeatures(BufferedImage image) throws Exception {
		long start = System.currentTimeMillis();
		double[][] features = extractFeaturesInternal(image);
		totalNumberInterestPoints += features.length;
		totalExtractionTime += System.currentTimeMillis() - start;
		return features;
	}
520731
def _check_input(image, init_level_set):
    """"""
    if not image.ndim in [2, 3]:
        raise ValueError("`image` must be a 2 or 3-dimensional array.")

    if len(image.shape) != len(init_level_set.shape):
        raise ValueError("The dimensions of the initial level set do not "
                         "match the dimensions of the image.")
205559
def preprocess(net, image):
    '''
    
    '''
    return np.float32(np.rollaxis(image, 2)[::-1]) - net.transformer.mean["data"]