Created
January 18, 2016 01:19
-
-
Save pebbie/1ba3786a1bccb80f22f0 to your computer and use it in GitHub Desktop.
automatic roi selector based on automatic scale selection fixed at single point
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| author : Peb Ruswono Aryan | |
| Automatic selection of ROI rectangle based on single point (assumed target center) selection on the image | |
| Automatic scale selection performed by selecting scale which maximizes laplacian of gaussian in the selected point across scales | |
| intended use : simplifying object tracking target selection, output rectangle can be used as initial target | |
| """ | |
| import os | |
| import sys | |
| import cv2 | |
| import numpy as np | |
| from math import floor, ceil | |
| def find_optimal_window(img, x, y): | |
| STEP = 6 | |
| BASE = 3 | |
| pyr = [img] | |
| pt = (x,y) | |
| pts = [(1.*pt[0], 1.*pt[1])] | |
| val = [sample_point(LoG(pyr[0]), pts[0][0], pts[0][1])] | |
| w = [BASE] | |
| for i in range(STEP): | |
| pyr.append(cv2.pyrDown(pyr[-1])) | |
| pts.append((pts[-1][0]*0.5, pts[-1][1]*0.5)) | |
| val.append(sample_point(LoG(pyr[i+1]), pts[i+1][0], pts[i+1][1])) | |
| w.append(w[-1]*2) | |
| return w[np.argmax(np.abs(np.array(val)))] | |
| def mouseHandler(e, x, y, flags, params): | |
| global img | |
| if e == cv2.EVENT_LBUTTONDOWN: | |
| optimal_width = find_optimal_window(gr, x, y) | |
| mid = optimal_width / 2 | |
| imc = img.copy() | |
| cv2.circle(imc, (x, y), 1, (0,255,255)) | |
| cv2.rectangle(imc, (int(x-mid), int(y-mid)), (int(x+mid), int(y+mid)), (0,255,255)) | |
| cv2.imshow("select", imc) | |
| def sample_point(img, x, y): | |
| x1 = int(floor(x)) | |
| y1 = int(floor(y)) | |
| x2 = int(ceil(x)) | |
| y2 = int(ceil(y)) | |
| v1 = img[y1,x1] | |
| v2 = img[y1,x2] | |
| v3 = img[y2,x1] | |
| v4 = img[y2,x2] | |
| alpha = x-x1 | |
| beta = y-y1 | |
| vh1 = v1 * (1.-alpha) + v2 * (alpha) | |
| vh2 = v3 * (1.-alpha) + v4 * (alpha) | |
| return vh1 * (1.-beta) + vh2 * (beta) | |
| def LoG(img): | |
| G = cv2.GaussianBlur(img, (3,3), 2) | |
| L = cv2.Laplacian(G, cv2.CV_32F) | |
| return L | |
| if __name__=="__main__": | |
| fn = "warna.jpg" | |
| if len(sys.argv)>1 and os.path.exists(sys.argv[1]): | |
| fn = sys.argv[1] | |
| cv2.namedWindow("select") | |
| cv2.setMouseCallback("select", mouseHandler, None) | |
| img = cv2.imread(fn) | |
| gr = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
| cv2.imshow("select", img) | |
| while True: | |
| k = cv2.waitKey(1) | |
| if k == 27 or k == ord('q'): | |
| break | |
| cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sample_point is not working