def applyThreshold(self, imgf, threshold): _, imgf = cv2.threshold(imgf,threshold,255,cv2.THRESH_BINARY) if(self.traced): util.show('after tresh', imgf) imgf = cv2.bitwise_not(imgf) imgf = self.dilatation(imgf, id, 1) return imgf
def calcHistogramTrhreshold(self, imgf): hist = cv2.calcHist([imgf],[0],None,[256],[0,256]) threshold = 255 bins = len(hist) index = 0 total = 0; while( index < bins ): if(self.traced): util.output("hist "+ str(index)+ " value "+ str(hist[index])) total += hist[index] index += 1; soglia = total * 0.005 ; index = bins -1 cumulative = 0 while( index > 0 ): cumulative += hist[index] if( cumulative > soglia ): break; threshold -= 1 index -= 1 if(self.traced): util.output("Threshold is "+str(threshold)); if( threshold >= 254 ): threshold = 254 else: threshold += 1 self.threshold = threshold if(self.traced): util.show('before tresh', imgf) return threshold;
def make_topo_tomo_flat(args, highspeed=True, scintillator=None): syris.init(device_index=0, loglevel='INFO') dimax = make_pco_dimax() n = dimax.shape[0] energies = np.arange(5, 30) * q.keV bm, detector = make_devices(n, energies, camera=dimax, highspeed=highspeed, scintillator=scintillator) # Customize the setup for the 2013_03_07-08 experiment air = MaterialFilter(1 * q.m, get_material('air_5_30_kev.mat')) filters = [air] dimax.bpp = 32 dimax.dtype = np.float32 dimax.fps = 450 / q.s detector.lens.f_number = 2.8 bm.el_current = 130 * q.mA # Compte the flat field flat = get_flat(dimax.shape, energies, detector, bm, filters=filters, shot_noise=True, amplifier_noise=True) fmt = 'min: {}, max: {}, mean: {}, middle row std: {}' print fmt.format(flat.min(), flat.max(), flat.mean(), flat[n / 2].std()) show(flat) plt.show() return flat
def main(): """Main function.""" args = parse_args() syris.init(loglevel=logging.INFO, double_precision=args.double_precision) units = q.Quantity(1, args.units) triangles = make_cube( ).magnitude if args.input is None else read_blender_obj(args.input) triangles = triangles * units tr = geom.Trajectory([(0, 0, 0)] * units) mesh = Mesh(triangles, tr, center=args.center, iterations=args.supersampling) LOG.info('Number of triangles: {}'.format(mesh.num_triangles)) shape = (args.n, args.n) if args.pixel_size is None: if args.input is None: fov = 4. * units else: # Maximum sample size in x and y direction max_diff = np.max(mesh.extrema[:-1, 1] - mesh.extrema[:-1, 0]) fov = max_diff fov *= args.margin args.pixel_size = fov / args.n else: fov = args.n * args.pixel_size if args.translate is None: translate = (fov.simplified.magnitude / 2., fov.simplified.magnitude / 2., 0) * q.m else: translate = (args.translate[0].simplified.magnitude, args.translate[1].simplified.magnitude, 0) * q.m LOG.info('Translation: {}'.format(translate.rescale(q.um))) mesh.translate(translate) mesh.rotate(args.y_rotate, geom.Y_AX) mesh.rotate(args.x_rotate, geom.X_AX) fmt = 'n: {}, pixel size: {}, FOV: {}' LOG.info( fmt.format(args.n, args.pixel_size.rescale(q.um), fov.rescale(q.um))) st = time.time() proj = mesh.project(shape, args.pixel_size, t=None).get() LOG.info('Duration: {} s'.format(time.time() - st)) offset = (0, translate[1].simplified, -(fov / 2.).simplified) * q.m if args.projection_filename is not None: save_image(args.projection_filename, proj) if args.compute_slice: sl = mesh.compute_slices((1, ) + shape, args.pixel_size, offset=offset).get()[0] if args.slice_filename is not None: save_image(args.slice_filename, sl) show(sl, title='Slice at y = {}'.format(args.n / 2)) show(proj, title='Projection') plt.show()
def search_roi(): roi = util.load_img('img/roi.png') roi_hsv = util.hsv(roi) tar = util.load_img('img/tar.png') tar_hsv = util.hsv(tar) # 计算目标直方图 颜色直方图优于灰度直方图 roihist = cv.calcHist([roi_hsv], [0, 1], None, [180, 256], [0, 180, 0, 256]) # 对象直方图进行normalize cv.calcBackProject返回概率图像 cv.normalize(roihist, roihist, 0, 255, cv.NORM_MINMAX) dst = cv.calcBackProject([tar_hsv], [0, 1], roihist, [0, 180, 0, 256], 1) # 与disc kernel卷积 disc = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5)) cv.filter2D(dst, -1, disc, dst) # threshold and binary AND ret, thresh = cv.threshold(dst, 50, 255, 0) # 使用merge变成通道图像 thresh = cv.merge((thresh, thresh, thresh)) # 蒙板 res = cv.bitwise_and(tar, thresh) res = np.hstack((tar, thresh, res)) util.show(res)
def filter_musical_objects(img, objs): objs2 = [] img_color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) for r, c, w, h in objs: cv2.rectangle(img_color, (r, c), (r + w, c + h), util.RED, 1) img2 = cv2.GaussianBlur(img, (29, 29), 0) circles = cv2.HoughCircles(img2[c:c + h, r:r + w], cv2.cv.CV_HOUGH_GRADIENT, 1, 10, param1=50, param2=16) if circles is not None and len(circles[0]) == 1: objs2.append((r, c, w, h)) for x, y, rad in circles[0]: cv2.circle(img_color, ((int)(r + x), (int)(c + y)), rad, util.RED) util.show('Circles', img_color, True) return objs2
def get_texture_from_hue(hue, contour_box): # for convenience card_w = sc.SIZE_CARD_W card_h = sc.SIZE_CARD_H # uppack bounding box of contour x, y, w, h = contour_box # get a 20x20 square from each of the corners of the card, average values hue_bg = np.mean( [ hue[6:26, 6:26], hue[card_h - 26 : card_h - 6, card_w - 26 : card_w - 6], hue[6:26, card_w - 26 : card_w - 6], hue[card_h - 26 : card_h - 6, 6:26], ] ) # get a 20x20 square from the center of the shape, average values hue_center = np.mean(hue[y + h / 2 - 10 : y + h / 2 + 10, x + w / 2 - 10 : x + w / 2 + 10]) util.show(hue[y + h / 2 - 10 : y + h / 2 + 10, x + w / 2 - 10 : x + w / 2 + 10]) # guess texture based on ratio of inside to outside hues hue_ratio = max(hue_bg, hue_center) / min(hue_bg, hue_center) if hue_ratio < 1.3: return sc.PROP_TEXTURE_EMPTY elif hue_ratio < 2.8: return sc.PROP_TEXTURE_STRIPED else: return sc.PROP_TEXTURE_SOLID
def hough(): img = util.load_img('img/sudoku.png') img_gray = util.gray(img) edges = cv.Canny(img_gray, 100, 200) """cv.HoughLinesP""" lines = cv.HoughLinesP(edges, 1, np.pi / 180, 200, minLineLength=100, maxLineGap=10) for line in lines: x1, y1, x2, y2 = line[0] cv.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2) """cv.HoughLines""" # lines = cv.HoughLines(edges, 1, np.pi / 180, 200) # for line in lines: # rho, theta = line[0] # a = np.cos(theta) # b = np.sin(theta) # x0 = a * rho # y0 = b * rho # x1 = int(x0 + 1000 * (-b)) # y1 = int(y0 + 1000 * (a)) # x2 = int(x0 - 1000 * (-b)) # y2 = int(y0 - 1000 * (a)) # cv.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2) """""" util.show(img)
def get_card_properties_v2(card, debug=False): # convert to HSV colorspace and get binary representation of image bin_sat_val, hue, sat, val = get_binary_from_hsv(card) binary = cv2.bitwise_or(bin_sat_val, get_canny(card)) # get contours from binary image contours, contour_areas, contour_boxes, contour_centers = get_contour_info(binary, True) # crop image so we're only looking at the bounding rectangle x, y, w, h = contour_boxes[0] hue_crop = hue[y : y + h, x : x + w] # no more than 3 shapes per card prop_num_init = get_dropoff([b[2] * b[3] for b in contour_boxes], maxratio=1.2) prop_num = prop_num_init if prop_num_init < 3 else 3 prop_col = get_color_from_hue(hue_crop) prop_shp = get_shape_from_contour(contours[0], contour_boxes[0]) prop_tex = get_texture_from_hue_val(hue, val, contour_boxes[0]) if debug: pretty_print_properties([(prop_num, prop_col, prop_shp, prop_tex)]) util.show(card) return (prop_num, prop_col, prop_shp, prop_tex)
def main(): args = parse_args() syris.init() n = 1024 d = args.propagation_distance * q.m shape = (n, n) ps = 1 * q.um energy = 20 * q.keV tr = Trajectory([(n / 2, n / 2, 0)] * ps, pixel_size=ps) sample = make_sphere(n, n / 30 * ps, pixel_size=ps, material=get_material('air_5_30_kev.mat')) bm = make_topotomo(pixel_size=ps, trajectory=tr) print 'Source size FWHM (height x width): {}'.format(bm.size.rescale(q.um)) u = bm.transfer(shape, ps, energy, t=0 * q.s) u = sample.transfer(shape, ps, energy) intensity = propagate([sample], shape, [energy], d, ps).get() incoh = bm.apply_blur(intensity, d, ps).get() region = (n / 4, n / 4, n / 2, n / 2) intensity = ip.crop(intensity, region).get() incoh = ip.crop(incoh, region).get() show(intensity, title='Coherent') show(incoh, title='Applied source blur') plt.show()
def hull_(): """ 类似于轮廓近似 凸壳 在多维空间中有一群散佈各处的点 凸包 是包覆这群点的所有外壳当中,表面积暨容积最小的一个外壳,而最小的外壳一定是凸的 凸: 图形内任意两点的连线不会经过图形外部 """ img = util.load_img('img/horse.png') convex = util.load_img('img/horse1.png') height = img.shape[0] width = img.shape[0] out = util.blank_img(width * 1.5, height, (255, 255, 255)) # 求轮廓 contours = get_cnt(img) convex_cnt = get_cnt(convex)[0] # 求凸包 cv.drawContours(out, contours, -1, (255, 0, 0), 5) cnt = contours[0] hull = cv.convexHull(cnt) # 检测一个曲线是不是凸的 print(cv.isContourConvex(cnt)) cv.drawContours(out, [hull], -1, (0, 0, 255), 5) util.show(out)
def feature(): src = util.load_img('img/s.png') # img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) ret, thresh = cv.threshold(src, 127, 255, cv.THRESH_BINARY) # cv.findContours()函数中有三个参数,第一个是源图像,第二个是轮廓检索模式,第三个是轮廓近似方法。它输出轮廓和层次结构 contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) # 第一个参数是源图像,第二个参数是轮廓,第三个参数是轮廓索引 -1是所有轮廓 其余参数是颜色,厚度 # res = cv.drawContours(src, contours, -1, (0, 255, 0), 3) # util.show(res) height = src.shape[0] width = src.shape[0] out = util.blank_img(width * 1.5, height, (255, 255, 255)) # util.show(img) for index, cnt in enumerate(contours): # 画轮廓 cv.drawContours(out, contours, index, (0, 0, 255), 1) # 质心坐标 M = cv.moments(cnt) cx = M['m10'] / M['m00'] cy = M['m01'] / M['m00'] cv.circle(out, (int(cx), int(cy)), 2, (255, 0, 0), -1) # 轮廓面积 M['m00'] area = cv.contourArea(cnt) # 轮廓周长 轮廓是否闭合True perimeter = cv.arcLength(cnt, True) print('({},{}) 面积={} 周长={}'.format(cx, cy, area, perimeter)) util.show(out)
def showSuperImposedImages(self, offset, angle): cols = self.dataReference.width rows = self.dataReference.height #rotation rotation = cv2.getRotationMatrix2D( (self.dataReference.cm.x, self.dataReference.cm.y), angle, 1) rotated = cv2.warpAffine(self.dataReference.image, rotation, (cols, rows)) # translate reference translation = np.float32([[1, 0, int(offset.x)], [0, 1, int(offset.y)]]) rotatedAndTranslated = cv2.warpAffine(rotated, translation, (cols, rows)) colorTentative = cv2.cvtColor(self.dataTentative.image, cv2.COLOR_GRAY2BGR) rotatedAndTranslated = cv2.cvtColor(rotatedAndTranslated, cv2.COLOR_GRAY2BGR) print(rotatedAndTranslated.shape) print(colorTentative.shape) finalImage = cv2.addWeighted(rotatedAndTranslated, 0.7, colorTentative, 0.3, 0) self.dataReference.drawDestinationPoints(finalImage, offset, angle, self.dataTentative.hits, self.dataTentative.points, self.dataReference.cm) util.show('final', finalImage)
def train(m, p=None): d = DataLoader(BSD3000(), o.batch_size, num_workers=o.num_workers) optimizer = torch.optim.Adam(m.parameters(), lr=o.lr) iter_num = len(d) num = 0 losss = [] stage = 1 if not p else p.stage + 1 for epoch in range(o.epoch): for i in tqdm(d): g, y, k, s = [x.to(o.device) for x in i] x = y optimizer.zero_grad() out = m(x) log("out", out) loss = npsnr(out, g) loss.backward() optimizer.step() losss.append(loss.detach().item()) assert not isnan(losss[-1]) print("stage", stage, "epoch", epoch + 1) log("loss", mean(losss[-5:])) num += 1 # if num > (o.epoch * iter_num - 4): if num % 50 == 1: show(torch.cat((y[0, 0], g[0, 0], out[0, 0]), 1), # save=f"save/{stage:02}{epoch:02}.png", ) plt.clf() plt.plot(range(len(losss)), losss) plt.xlabel("batch") plt.ylabel("loss") plt.title(f"{iter_num} iter x {o.epoch} epoch") plt.savefig(f"save/{stage:02}loss.png")
def calculatePoints(self, imgf, threshold): imgf = self.applyThreshold(imgf, threshold) imgInverted = cv2.bitwise_not(imgf) if(self.traced): util.show('Tracing this', imgInverted) mum_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(imgInverted) return mum_labels -1 ;
def test_single(self): saved = pickle.load(open("model.p", "rb")) t_labels = saved['labels'] t_desc = saved['desc'] img, target = next(self.teststream) _, des = self.KPD.detectAndCompute(img, None) res = [] for index, tdes in t_desc.items(): matches = self.bf.match(des, tdes) matches = sorted(matches, key=lambda x: x.distance) try: distance = sum([ 1 / float(x.distance) for x in matches[:self.num_matches] ]) / float(max(self.num_matches, len(matches))) except ZeroDivisionError: distance = 1 res.append((index, distance)) res = sorted(res, key=lambda x: x[1], reverse=True) top = [t_labels[l[0]] for l in res[:self.n]] if self.n == 0: pred = top[0] else: items, count = scipy.stats.mode(top) pred = items[0][max(range(len(items)), key=lambda x: count[x])] print('Label: {} ({})'.format(target, label_dict[target])) print('Prediction: {} ({})'.format(pred, label_dict[pred])) show(img)
def side(doc,grp): points = [ xy(-511,-825), xy(-550,-491), xy(-383,-395), xy(-85,-465), xy(85,-225), xy(299,-19), xy(433,-237), xy(415,-610), xy(380,-702), xy(183,-922) ] #s = Draft.makeBSpline(points,closed=False) #grp.addObject(s) sp = Part.BSplineCurve() sp.interpolate(points,True) w = Part.Wire(sp.toShape()) f = Part.Face(w) x = f.extrude(z(thicknessSide)) c = Part.makeCylinder(r,thicknessSide,O,z(1)) util.show(Part.makeSphere(10, O)) y = x.common(c) y.translate(z(-thicknessSide)) x = rich(y).rotO(z(1),20+angle) c = x.Solids[0].CenterOfMass util.show(Part.makeSphere(50, c)) return x
def draw(): # 画图窗口大小设置为512*512 通常参数,可选1,3,4 img = np.zeros((512, 512, 4), np.uint8) # 画直线,参数为绘图窗口,起点,终点,颜色,粗细,连通性(可选4联通或8联通) img = cv.line(img, (100, 0), (511, 511), (255, 0, 0), 5, 8) # 画矩形,参数为窗口,左上角坐标,右下角坐标,颜色,粗度 img = cv.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3) # 画圆函数,参数为窗口,圆心,半径,颜色,粗度(如果粗度为-1标示实心),连通性 img = cv.circle(img, (447, 63), 50, (0, 0, 255), 1, 8) # 画椭圆函数,参数为窗口,椭圆中心,椭圆长轴短轴,椭圆逆时针旋转角度,椭圆起绘制起始角度,椭圆绘制结束角度,颜色,粗度,连通性 img = cv.ellipse(img, (256, 256), (100, 50), 100, 36, 360, (0, 255, 255), 1, 8) # 画多边形 pts = np.array([[10, 5], [20, 30], [70, 20], [50, 10]], np.int32) # 转换成三维数组,表示每一维里有一个点坐标 pts = pts.reshape((-1, 1, 2)) # 画多边形函数,参数为窗口,坐标,是否封闭,颜色 img = cv.polylines(img, [pts], True, (0, 255, 255)) # 字 参数为窗口,字符,字体位(左下角),字体类型(查询cv2.putText()函数的文档来查看字体),字体大小,常规参数,类似颜色,粗细,线条类型等等 font = cv.FONT_HERSHEY_SIMPLEX cv.putText(img, 'OpenCV', (10, 500), font, 4, (255, 255, 255), 2, cv.LINE_AA) util.show(img)
def make_motion(args): syris.init() n = 256 shape = (n, n) energies = np.arange(5, 30, 1) * q.keV bm, detector = make_devices(n, energies) mb = create_sample(n, detector.pixel_size, velocity=20 * q.mm / q.s) mb_2 = create_sample(n, detector.pixel_size, velocity=10 * q.mm / q.s) mb.material = get_material('pmma_5_30_kev.mat') mb_2.material = mb.material cube = make_cube() / q.m * 30 * detector.pixel_size + 0.1 * detector.pixel_size fov = detector.pixel_size * n circle = make_circle().magnitude * fov / 30000 + fov / 2 tr = Trajectory(circle, velocity=10 * q.um / q.s) glass = get_material('glass.mat') mesh = Mesh(cube, tr, material=glass) ex = Experiment([bm, mb, mb_2, mesh], bm, detector, 0 * q.m, energies) for sample in ex.samples: if sample != bm: sample.trajectory.bind(detector.pixel_size) if args.show_flat: show(get_flat(shape, energies, detector, bm), title='Counts') plt.show() if args.conduct: if args.output is not None and not os.path.exists(args.output): os.makedirs(args.output, mode=0o755) t_0 = 0 * q.s if args.num_images: t_1 = args.num_images / detector.camera.fps else: t_1 = ex.time st = time.time() mpl_im = None for i, proj in enumerate(ex.make_sequence(t_0, t_1)): image = get_host(proj) if args.show: if mpl_im is None: plt.figure() mpl_im = plt.imshow(image) plt.show(False) else: mpl_im.set_data(image) plt.draw() if args.output: path = os.path.join(args.output, 'projection_{:>05}.png').format(i) scipy.misc.imsave(path, image) print 'Maximum intensity:', image.max() print 'Duration: {} s'.format(time.time() - st) plt.show()
def plot_graph(g, s, t, path=[], cover=False): plt.clf() g.plot() g.plot_path(path) g.plot_st(s, t) if cover: util.plot_cover([g.pos[u] for u in g.photo_nodes()], RADIUS) util.show()
def test_props(img): color = sc.PROP_COLOR_MAP[s.get_card_color(img)] shape = sc.PROP_SHAPE_MAP[s.get_card_shape(img, s.get_training_set())] num = s.get_card_number(img) texture = sc.PROP_TEXTURE_MAP[s.get_card_texture(img)] print '%d %s %s %s' % (num, color, shape, texture) print('---') util.show(img)
def main(): syris.init() energies = np.arange(10, 30) * q.keV n = 1024 pixel_size = 0.4 * q.um distance = 2 * q.m material = make_henke('PMMA', energies) sample = make_sphere(n, n / 4 * pixel_size, pixel_size, material=material) image = propagate([sample], (n, n), energies, distance, pixel_size).get() show(image) plt.show()
def commandReceived(command_string): if command_string == 'Disconnected': print('Disconnected') return if command_string == 'op': print('Show window!') util.show() elif command_string == 'cl': print('Attempting to minimize window') util.hide() renderer.resetAll() else: renderer.select(command_string)
def approx(): img = util.load_img('img/t.png') height = img.shape[0] width = img.shape[0] out = util.blank_img(width * 1.5, height, (255, 255, 255)) contours = get_cnt(img) # a = cv.drawContours(out, contours, -1, (255, 0, 0), 5) epsilon = 1 * cv.arcLength(contours[0], True) approx = cv.approxPolyDP(contours[0], epsilon, True) cv.drawContours(out, [approx], -1, (0, 0, 255), 5) util.show(out)
def main(): args = parse_args() syris.init() n = 1024 shape = (n, n) ps = 1 * q.um tr = Trajectory([(n / 2, n / 2, 0)] * ps, pixel_size=ps) energy_center = args.energy_center * q.keV fwhm = args.energy_resolution * energy_center sigma = smath.fwnm_to_sigma(fwhm, n=2) # Make sure we resolve the curve nicely energies = np.arange(max(1 * q.keV, energy_center - 2 * fwhm), energy_center + 2 * fwhm, fwhm / 25) * q.keV dE = energies[1] - energies[0] print 'Energy from, to, step, number:', energies[0], energies[-1], dE, len( energies) bm = make_topotomo(dE=dE, pixel_size=ps, trajectory=tr) spectrum_energies = np.arange(1, 50, 1) * q.keV native_spectrum = get_spectrum(bm, spectrum_energies, ps) fltr = GaussianFilter(energies, energy_center, sigma) gauss = get_gauss(energies.magnitude, energy_center.magnitude, sigma.magnitude) filtered_spectrum = get_spectrum(bm, energies, ps) * gauss intensity = propagate([bm, fltr], shape, energies, 0 * q.m, ps).get() show(intensity, title='Intensity for energy range {} - {}'.format( energies[0], energies[-1])) plt.figure() plt.plot(spectrum_energies.magnitude, native_spectrum) plt.title('Source Spectrum') plt.xlabel('Energy [keV]') plt.ylabel('Intensity') plt.figure() plt.plot(energies.magnitude, gauss) plt.title('Gaussian Filter') plt.xlabel('Energy [keV]') plt.ylabel('Transmitted intensity') plt.figure() plt.plot(energies.magnitude, filtered_spectrum) plt.title('Filtered Spectrum') plt.xlabel('Energy [keV]') plt.ylabel('Intensity') plt.show()
def water(): """ 使用距离变换和分水岭来分割相互接触的物体 靠近对象中心的区域是前景,离对象远的区域是背景,不确定的区域是边界。 物体没有相互接触/只求前景 可用侵蚀消除了边界像素 到距离变换并应用适当的阈值 膨胀操作会将对象边界延伸到背景,确保background区域只有background 边界 = 能否确认是否是背景的区域 - 确定是前景的区域 """ img = util.load_img('img/coins.png') gray = util.gray(img) ret, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU) util.show(thresh) # noise removal kernel = np.ones((3, 3), np.uint8) opening = cv.morphologyEx(thresh, cv.MORPH_OPEN, kernel, iterations=2) # sure background area sure_bg = cv.dilate(opening, kernel, iterations=3) # Finding sure foreground area dist_transform = cv.distanceTransform(opening, cv.DIST_L2, 5) # 计算每个像素离最近0像素的距离 ret, sure_fg = cv.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0) # Finding unknown region sure_fg = np.uint8(sure_fg) unknown = cv.subtract(sure_bg, sure_fg) # Marker labelling 用0标记图像的背景 其他对象用从1开始的整数标记 ret, markers = cv.connectedComponents(sure_fg) """ 我们知道,如果背景标记为0,分水岭会将其视为未知区域。所以我们想用不同的整数来标记它。相反,我们将标记由未知定义的未知区域,为0。 """ # Add one to all labels so that sure background is not 0, but 1 markers = markers + 1 # Now, mark the region of unknown with zero markers[unknown == 255] = 0 markers = cv.watershed(img, markers) # 修改标记图像。边界区域将标记为-1 img[markers == -1] = [255, 0, 0] util.show(img, is_seq=True)
def more_temp(): """匹配多个对象""" img_rgb = util.load_img('img/mario.png') img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY) template = cv.imread('img/mario_coin.png', 0) w, h = template.shape[::-1] res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED) print(res.shape) threshold = 0.8 # 注意 行列 高宽 loc = np.where(res >= threshold) for pt in zip(*loc[::-1]): cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2) util.show(img_rgb)
def make_trajectory_sequence(args): # Make a small circle (1 / 10 of the pixel size), so that the composite body only rotates and # does not translate. Put this circle in the middle of the image. circle = args.n / 2 * args.ps + make_circle(n=1024).magnitude * args.ps / 10 traj = Trajectory(circle, velocity=args.ps / q.s, pixel_size=args.ps) metaballs = _make_metaballs(args) composite = CompositeBody(traj, bodies=metaballs) im = None d_angle = 10 * q.deg fmt = 'Projection at rotation {:>9}' # Rotate around 360 deg for i, t in enumerate(np.linspace(0, traj.time.simplified.magnitude, 37) * q.s): # Reset transformation matrices composite.clear_transformation() # Move to the desired position, i.e. around the circle and then each metaball moves relative # to the composite body. composite.move(t) p = composite.project(args.shape, args.ps).get() if im is None: im = show(p, title=fmt.format(i * d_angle)) else: im.axes.set_title(fmt.format(i * d_angle)) im.set_data(p) plt.draw() plt.show()
def cleanWithExpectedCount(self, img, id, target): if(self.writeOp): util.show('orig',img) imgf = self.prepare(img, 'orig'); if(self.writeOp): util.show('prepared',imgf) num_points = 0; target_value = int(target*1.1) nuova_soglia = 256 while((num_points<target_value) and (nuova_soglia>=0) ): nuova_soglia = nuova_soglia -1 ; num_points = self.calculatePoints(imgf, nuova_soglia) if(self.writeOp): util.output("Test for threshold "+ str(nuova_soglia)+" Points #: "+ str(num_points)); self.soglia = nuova_soglia+1; return self.applyThreshold(imgf, self.soglia)
def make_manual_sequence(args): metaballs = _make_metaballs(args) traj = Trajectory([(args.n / 2., args.n / 2., 0)] * args.ps, pixel_size=args.ps) composite = CompositeBody(traj, bodies=metaballs) # Move the sub-bodies relative to the composite body and also move the composite body to the # center of the image. composite.move(0 * q.s) im = None d_angle = 10 * q.deg fmt = 'Projection at rotation {:>9}' # Rotate around 360 deg for i in range(int((360 * q.deg / d_angle).magnitude) + 1): p = composite.project(args.shape, args.ps).get() if im is None: im = show(p, title=fmt.format(i * d_angle)) else: im.axes.set_title(fmt.format(i * d_angle)) im.set_data(p) plt.draw() # Rotation takes care of the relative rotation of the sub-bodies around the composite body. composite.rotate(d_angle, geom.Z_AX) plt.show()
def make_trajectory_sequence(args): # Make a small circle (1 / 10 of the pixel size), so that the composite body only rotates and # does not translate. Put this circle in the middle of the image. circle = args.n / 2 * args.ps + make_circle( n=1024).magnitude * args.ps / 10 traj = Trajectory(circle, velocity=args.ps / q.s, pixel_size=args.ps) metaballs = _make_metaballs(args) composite = CompositeBody(traj, bodies=metaballs) im = None d_angle = 10 * q.deg fmt = 'Projection at rotation {:>9}' # Rotate around 360 deg for i, t in enumerate( np.linspace(0, traj.time.simplified.magnitude, 37) * q.s): # Reset transformation matrices composite.clear_transformation() # Move to the desired position, i.e. around the circle and then each metaball moves relative # to the composite body. composite.move(t) p = composite.project(args.shape, args.ps).get() if im is None: im = show(p, title=fmt.format(i * d_angle)) else: im.axes.set_title(fmt.format(i * d_angle)) im.set_data(p) plt.draw() plt.show()
def main(): args = parse_args() syris.init() n = 1024 shape = (n, n) ps = 1 * q.um tr = Trajectory([(n / 2, n / 2, 0)] * ps, pixel_size=ps) energy_center = args.energy_center * q.keV fwhm = args.energy_resolution * energy_center sigma = smath.fwnm_to_sigma(fwhm, n=2) # Make sure we resolve the curve nicely energies = np.arange(max(1 * q.keV, energy_center - 2 * fwhm), energy_center + 2 * fwhm, fwhm / 25) * q.keV dE = energies[1] - energies[0] print 'Energy from, to, step, number:', energies[0], energies[-1], dE, len(energies) bm = make_topotomo(dE=dE, pixel_size=ps, trajectory=tr) spectrum_energies = np.arange(1, 50, 1) * q.keV native_spectrum = get_spectrum(bm, spectrum_energies, ps) fltr = GaussianFilter(energies, energy_center, sigma) gauss = get_gauss(energies.magnitude, energy_center.magnitude, sigma.magnitude) filtered_spectrum = get_spectrum(bm, energies, ps) * gauss intensity = propagate([bm, fltr], shape, energies, 0 * q.m, ps).get() show(intensity, title='Intensity for energy range {} - {}'.format(energies[0], energies[-1])) plt.figure() plt.plot(spectrum_energies.magnitude, native_spectrum) plt.title('Source Spectrum') plt.xlabel('Energy [keV]') plt.ylabel('Intensity') plt.figure() plt.plot(energies.magnitude, gauss) plt.title('Gaussian Filter') plt.xlabel('Energy [keV]') plt.ylabel('Transmitted intensity') plt.figure() plt.plot(energies.magnitude, filtered_spectrum) plt.title('Filtered Spectrum') plt.xlabel('Energy [keV]') plt.ylabel('Intensity') plt.show()
def evaluate(model, x_global, x_local, x_ctx, box, texts, verbose=True, **params): if verbose: img = x_global - x_global.min() util.show(x_local) util.show(img, box=box) candidate = predict(model, x_global, x_local, x_ctx, box, **params) candidate = util.strip(candidate) references = map(util.strip, texts) #print("{} {} ({})".format(likelihood, candidate, references[0])) return candidate, references
def main(): syris.init() n = 256 shape = (n, n) ps = 1 * q.um fov = n * ps triangles = make_cube().magnitude * n / 8. * ps # Rotation around the vertical axis points = make_circle(axis='y').magnitude * fov / 30000 + fov / 2 trajectory = geom.Trajectory(points, pixel_size=ps, velocity=10 * q.um / q.s) # *orientation* aligns the object with the trajectory derivative mesh = Mesh(triangles, trajectory, orientation=geom.Z_AX) # Compute projection at the angle Pi/4 projection = mesh.project(shape, ps, t=trajectory.time / 8).get() show(projection) plt.show()
def rect(): img = util.load_img('img/rect.png') contours = get_cnt(img) height = img.shape[0] width = img.shape[0] # out = util.blank_img(width * 1.5, height, (255, 255, 255)) out = img # out = img for index, cnt in enumerate(contours): x, y, w, h = cv.boundingRect(cnt) # 原型轮廓 红 cv.drawContours(out, contours, index, (0, 0, 255), 3) # 直边矩形 绿 cv.rectangle(out, (x, y), (x + w, y + h), (0, 255, 0), 2) # 最小面积绘制边界矩形 蓝 rect = cv.minAreaRect(cnt) box = cv.boxPoints(rect) box_ = np.int0(box) cv.drawContours(out, [box_], 0, util.rgb2bgr((30, 144, 255)), 2) # 最小封闭圈 橙 (x, y), radius = cv.minEnclosingCircle(cnt) center, radius = (int(x), int(y)), int(radius) cv.circle(out, center, radius, util.rgb2bgr((255, 140, 0)), 2) # 拟合椭圆 蓝 ellipse = cv.fitEllipse(cnt) cv.ellipse(out, ellipse, util.rgb2bgr((135, 206, 250)), 2) print(index) # # 线 黑 # rows, cols = out.shape[:2] # [vx, vy, x, y] = cv.fitLine(cnt, cv.DIST_L2, 0, 0.01, 0.01) # lefty = int((-x * vy / vx) + y) # righty = int(((cols - x) * vy / vx) + y) # print((cols - 1, righty), (0, lefty)) # cv.line(out, (cols - 1, righty), (0, lefty), (0, 0, 0), 2) # util.show(out) util.show(out)
def test(m): m.eval() with torch.no_grad(): d = DataLoader(Sun(), 1) losss = [] for i in tqdm(d): g, y, k, s = [x.to(o.device) for x in i] out = m([y, y, k, s]) out = crop(out, k) out = center_crop(out, *g.shape[-2:]) loss = npsnr(out, g) losss.append(-loss.detach().item()) log("psnr", losss[-1]) show( torch.cat( (center_crop(y, *g.shape[-2:])[0, 0], g[0, 0], out[0, 0]), 1)) log("psnr avg", sum(losss) / len(losss))
def more(): img = util.load_img('img/star.png') contours = get_cnt(img) cnt = contours[0] # 凸包时传递returnPoints = False,以便找到凸起缺陷 hull = cv.convexHull(cnt, returnPoints=False) defects = cv.convexityDefects(cnt, hull) for i in range(defects.shape[0]): # 起点,终点,最远点,到最远点的近似距离 s, e, f, d = defects[i, 0] start = tuple(cnt[s][0]) end = tuple(cnt[e][0]) far = tuple(cnt[f][0]) cv.line(img, start, end, [0, 255, 0], 2) cv.circle(img, far, 5, [0, 0, 255], -1) util.show(img)
def main(): args = parse_args() syris.init() # Propagate to 20 cm d = 5 * q.cm # Compute grid n_camera = 256 n = n_camera * args.supersampling shape = (n, n) material = get_material('pmma_5_30_kev.mat') energy = 15 * q.keV ps = 1 * q.um ps_hd = ps / args.supersampling radius = n / 4. * ps_hd fmt = ' Wavelength: {}' print fmt.format(energy_to_wavelength(energy)) fmt = 'Pixel size used for propagation: {}' print fmt.format(ps_hd.rescale(q.um)) print ' Field of view: {}'.format(n * ps_hd.rescale(q.um)) fmt = ' Sphere diameter: {}' print fmt.format(2 * radius) sample = make_sphere(n, radius, pixel_size=ps_hd, material=material) projection = sample.project((n, n), ps_hd).get() * 1e6 projection = decimate(projection, (n_camera, n_camera), average=True).get() # Propagation with a monochromatic plane incident wave hd = propagate([sample], shape, [energy], d, ps_hd).get() ld = decimate(hd, (n_camera, n_camera), average=True).get() kernel = compute_tie_kernel(n_camera, ps, d, material, energy) mju = material.get_attenuation_coefficient(energy).rescale(1 / q.m).magnitude f_ld = fft_2(ld) f_ld *= get_array(kernel.astype(cfg.PRECISION.np_float)) retrieved = ifft_2(f_ld).get().real retrieved = -1 / mju * np.log(retrieved) * 1e6 show(hd, title='High resolution') show(ld, title='Low resolution (detector)') show(retrieved, title='Retrieved [um]') show(projection, title='Projection [um]') show(projection - retrieved, title='Projection - retrieved') plt.show()
def make_complex_trajectory_sequence(args): edge = 20 x = np.linspace(0, args.n / 2 - args.n / 4 - edge - 5, num=10) y = z = np.zeros(x.shape) # Move along x axis traj_x = Trajectory(zip(x, y, z) * args.ps, velocity=args.ps / q.s, pixel_size=args.ps) # Move along y axis traj_y = Trajectory(zip(y, x, z) * args.ps, velocity=args.ps / q.s, pixel_size=args.ps) # Move along both x and y axes traj_xy = Trajectory(zip(x, x, z) * args.ps, velocity=args.ps / q.s, pixel_size=args.ps) # Circular trajectory of the composite body rotates around the image center and with radius # n / 4 pixels. circle = args.n / 2 * args.ps + make_circle().magnitude * args.n / 4 * args.ps traj_circle = Trajectory(circle, velocity=args.ps / q.s, pixel_size=args.ps) # Make the trajectory of the circle the same duration as the simple linear one. traj_circle = Trajectory(circle, velocity=traj_circle.length / traj_xy.length * args.ps / q.s) # three cubes in the same height and depth, shifted only along the x axis. traj_stationary = Trajectory([(0, 0, 0)] * args.ps) traj_stationary_1 = Trajectory([(-2 * edge, 0, 0)] * args.ps) traj_stationary_2 = Trajectory([(2 * edge, 0, 0)] * args.ps) cube = make_cube() / q.m * edge * args.ps # The cubes are elongated along y axis. cube[::2, :] /= 3 mesh = Mesh(cube, traj_x, orientation=geom.Y_AX) mesh_2 = Mesh(cube, traj_y, orientation=geom.Y_AX) mesh_3 = Mesh(cube, traj_xy, orientation=geom.Y_AX) mesh_stationary = Mesh(cube, traj_stationary, orientation=geom.Y_AX) mesh_stationary_1 = Mesh(cube, traj_stationary_1, orientation=geom.Y_AX) mesh_stationary_2 = Mesh(cube, traj_stationary_2, orientation=geom.Y_AX) bodies = [mesh, mesh_2, mesh_3, mesh_stationary, mesh_stationary_1, mesh_stationary_2] composite = CompositeBody(traj_circle, bodies=bodies, orientation=geom.Y_AX) composite.bind_trajectory(args.ps) total_time = composite.time if args.t is None: times = np.linspace(0, 1, 100) else: if args.t < 0 or args.t > 1: raise ValueError('--t must be in the range [0, 1]') times = [args.t] im = None for index, i in enumerate(times): t = i * total_time composite.clear_transformation() composite.move(t) p = composite.project(args.shape, args.ps).get() if im is None: im = show(p, title='Projection') else: im.set_data(p) plt.draw() plt.show()
def test(t, ml, mg): destroy('canny') # filename = 'images/brooklyn-bridge.jpg' filename = 'images/shapes.png' img = cv2.imread(filename, 0) print(img) color_img = cv2.imread(filename) canny_edges = canny(img) c = cv2.cvtColor(canny_edges, cv2.COLOR_GRAY2RGB) hough(canny_edges, c, t) lines, l_sum, l_avg = hough_p(canny_edges, c, t, ml, mg) print 'threshold: %d, min_line_len, %d, max_gap: %d\n%d lines found' \ % (t, ml, mg, lines) print 'sum is %d' % l_sum print 'avg is %d' % l_avg show(c, 'canny')
def filter_musical_objects(img, objs): objs2 = [] img_color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) for r, c, w, h in objs: cv2.rectangle(img_color, (r, c), (r+w, c+h), util.RED, 1) img2 = cv2.GaussianBlur(img, (29, 29), 0) circles = cv2.HoughCircles(img2[c:c+h, r:r+w], cv2.cv.CV_HOUGH_GRADIENT, 1, 10, param1=50,param2=16) if circles is not None and len(circles[0]) == 1: objs2.append((r, c, w, h)) for x, y, rad in circles[0]: cv2.circle(img_color, ((int)(r+x), (int)(c+y)), rad, util.RED) util.show('Circles', img_color, True) return objs2
def clean(self, img, id): if(self.writeOp): util.show('orig',img) imgf = self.prepare(img, 'orig'); if(self.writeOp): util.show('prepared',imgf) soglia = self.calcHistogramTrhreshold(imgf); nuova_soglia = soglia ; num_points = 10000; while(num_points>100): nuova_soglia = nuova_soglia +1 ; num_points = self.calculatePoints(imgf, nuova_soglia) if(self.writeOp): util.output("Test for threshold "+ str(nuova_soglia)+" Points #: "+ str(num_points)); if(num_points <= 0): nuova_soglia = nuova_soglia -1 ; break; self.soglia = nuova_soglia; return num_points, self.applyThreshold(imgf, self.soglia)
def trans(): """ translation, rotation, affine transformation img.shape height width channel x 横坐标 y 纵坐标 resize( (width,height),fx,fy (因子) ) cv.INTER_AREA for 缩小 cv.INTER_LINEAR for 放大 default cv.INTER_CUBIC slow :return: """ # img = util.load_img('img/messi5.jpg') # height, width = img.shape[:2] # print(img.shape) # res = cv.resize(img, None, fx=3, fy=2, interpolation=cv.INTER_LINEAR) # res = cv.resize(img, (int(0.5 * width), int(0.5 * height)), interpolation=cv.INTER_AREA) # # print(res.shape) # util.show(res) """ 平移 (100,50) """ img = util.load_img('img/messi5.jpg', 0) print(img.shape) rows, cols = img.shape M = np.float32([[1, 0, 100], [0, 1, 50]]) dst = cv.warpAffine(img, M, (cols, rows)) print(dst.shape) util.show(dst) """ 旋转 90度 """ rows, cols = img.shape # cols-1 and rows-1 are the coordinate limits. # center, angle, scale M = cv.getRotationMatrix2D(((cols - 1) / 2.0, (rows - 1) / 2.0), 90, 1) dst = cv.warpAffine(img, M, (cols, rows)) print(dst.shape) util.show(dst)
def main(): args = parse_args() syris.init(device_index=0) shape = (args.n, args.n) pixel_size = 1 * q.um if args.method == 'random': # Random metaballs creation metaballs, objects_all = create_metaballs_random(args.n, pixel_size, args.num, args.min_radius, args.max_radius) elif args.method == 'file': # 1e6 because packing converts to meters values = np.fromfile(args.input, dtype=np.float32) * 1e6 metaballs, objects_all = create_metaballs(values.reshape(len(values) / 4, 4)) else: distance = args.distance or args.n / 4 positions = [(args.n / 2 - distance, args.n / 2, 0, args.n / 6), (args.n / 2 + distance, args.n / 2, 0, args.n / 6)] metaballs, objects_all = create_metaballs(positions) if args.output: with open(args.output, mode='wb') as out_file: out_file.write(objects_all) z_min, z_max = get_z_range(metaballs) print 'z min, max:', z_min.rescale(q.um), z_max.rescale(q.um), args.n * pixel_size + z_min if args.algorithm == 'fast': traj = Trajectory([(0, 0, 0)] * q.m) comp = MetaBalls(traj, metaballs) thickness = comp.project(shape, pixel_size).get() else: print 'Z steps:', int(((z_max - z_min) / pixel_size).simplified.magnitude + 0.5) thickness = project_metaballs_naive(metaballs, shape, make_tuple(pixel_size)).get() if args.output_thickness: save_image(args.output_thickness, thickness) show(thickness) plt.show()
def main(): args = parse_args() syris.init(device_index=0) m = 20 if args.input == 'grid': image = make_grid(args.n, m * q.m).thickness.get() elif args.input == 'lena': from scipy.misc import lena image = lena().astype(cfg.PRECISION.np_float) if args.n != image.shape[0]: image = gutil.get_host(ip.rescale(image, (args.n, args.n))) n = image.shape[0] crop_n = n - 2 * m - 2 y, x = np.mgrid[-n / 2:n / 2, -n / 2:n / 2] # Compute a such that the disk diameter is exactly the period when distance from the middle is n # / 2 a = m / (2 * (crop_n / 2.) ** 2) radii = (a * np.sqrt(x ** 2 + y ** 2) ** 2 + 1e-3).astype(cfg.PRECISION.np_float) x_param = radii y_param = radii result = ip.varconvolve_disk(image, (y_param, x_param)).get() result = ip.crop(result, (m - 1, m - 1, crop_n, crop_n)).get() radii = ip.crop(radii, (m - 1, m - 1, crop_n, crop_n)).get() image = ip.crop(image, (m - 1, m - 1, crop_n, crop_n)).get() if args.output: save_image(args.output, result) show(image, title='Original Image') show(2 * radii, title='Blurring Disk Diameters') show(result, title='Blurred Image') plt.show()
def main(): args = parse_args() syris.init() n = 32 ps = 1 * q.um energies = np.arange(5, 30) * q.keV energy = 10 * q.keV lam = energy_to_wavelength(energy) # Delta causes phase shift between two adjacent pixels by 2 Pi delta = (lam / ps).simplified.magnitude ri = np.ones_like(energies.magnitude, dtype=np.complex) * delta + 0j material = Material('dummy', ri, energies) fmt = 'Computing with n: {:>4}, pixel size: {}' wedge = np.tile(np.arange(n), [n, 1]) * ps # Non-supersampled object shape causes phase shifts 0, 2Pi, 4Pi, ..., thus the phase is constant # as an extreme result of aliasing print fmt.format(n, ps) u = compute_transmission_function(n, ps, 1, energy, material) # Supersampling helps resolve the transmission function print fmt.format(n * args.supersampling, ps / args.supersampling) u_s = compute_transmission_function(n, ps, args.supersampling, energy, material) show(wedge.magnitude, title='Projected Object [um]') show(u.real, title='Re[T(x, y)]') show(u_s.real, title='Re[T(x, y)] Supersampled') plt.show()
def main(): syris.init() args = parse_args() n = 256 shape = (n, n) ps = 1 * q.um num_projections = None cube_edge = n / 4 * ps fmt = os.path.join(args.output, 'projection_{:04}.tif') x = np.linspace(n / 4 + n / 8, 3 * n / 4 + n / 8, num=10) y = z = np.zeros(x.shape) cube_0 = make_cube_body(n, ps, cube_edge) cube_1 = make_cube_body(n, ps, cube_edge, phase_shift=np.pi * q.rad) # Vertical motion component has such velocity that the cubes are displaced by their edge length # 1 pixel for making sure we have one "complete" sinogram velocity = (cube_edge - ps) / cube_0.trajectory.time traj_y = geom.Trajectory(zip(y, x, z) * ps, pixel_size=ps, velocity=velocity) composite = CompositeBody(traj_y, bodies=[cube_0, cube_1]) # Total time is the rotation time because we want one tomographic data set total_time = cube_0.trajectory.time dt = composite.get_next_time(0 * q.s, ps) if num_projections is None: num_projections = int(np.ceil((total_time / dt).simplified.magnitude)) print ' num_projs:', num_projections print ' rotation time:', cube_0.trajectory.time print ' vertical motion time:', traj_y.time print ' simulation time:', total_time for i in range(num_projections): t = total_time / num_projections * i composite.move(t) projection = composite.project(shape, ps).get() tifffile.imsave(fmt.format(i), projection) show(projection) plt.show()
def main(): # 3 of the 12 set that's bad cards_3_bad = cv2.imread('images/set-3-bad.jpg') thresh_3bad = s.get_binary(cards_3_bad) res3bad = s.detect_cards(cards_3_bad) assert res3bad is not None and len(res3bad) == 3 # 12 cards cards_12 = cv2.imread('images/set-12-random-2sets-sm.jpg') thresh_12bad = s.get_binary(cards_12) res12bad = s.detect_cards(cards_12, draw_rects=False) util.show(cards_12) # Subset of 3, with the 1 problem card cards = res12bad for i in range(len(cards)): card = cards[i] # test_props(card) cv2.imwrite('images/cards/card-12-%02d.jpg' % i, card) props = s.get_cards_properties(res12bad) s.pretty_print_properties(props) g = game(cards=props) sets = g.play(True) if sets: print '\nFound sets:' for st in sets: just_props = [e for i, e in st] print just_props s.pretty_print_properties(just_props) print('---') else: print 'no sets :(' print 'tests pass'
def test(): util.clear() reload(util); s = sBuild() bb = s.BoundBox box = util.box(max(1,bb.XLength),max(1,bb.YLength),max(1,bb.ZLength))\ .transO(v(bb.XMin,bb.YMin, bb.ZMin)) util.show(box) util.show(s) e = s.Edges[3] util.show(e) splits = util.splitFaceAlong(s,util.dir(e),[100,500,800]); util.addGroup("splits",map(lambda f: util.trimFace(f,10),splits))
def get_by_names(): """ One of the main ``clusto`` operations. Parameters: * Required parameter: At least one ``name`` parameter Returns ``HTTP: 404`` when all entites requested do not exist and ``HTTP: 206`` when a percent of entities requested do not exist. Examples: .. code:: bash $ ${get} ${server_url}/by-names "Provide at least one name to get data from" HTTP: 412 Content-type: application/json $ ${get} -d 'name=nonserver' ${server_url}/by-names [ null ] HTTP: 404 Content-type: application/json $ ${get} -d 'name=testserver1' -d 'name=nonserver' ${server_url}/by-names [ "/basicserver/testserver1", null ] HTTP: 206 Content-type: application/json $ ${get} -H 'Clusto-Mode: expanded' -d 'name=testserver1' -d 'name=testserver2' ${server_url}/by-names [ { "attrs": [], "contents": [], "driver": "basicserver", "name": "testserver1", "parents": [ "/pool/singlepool", "/pool/multipool" ] }, { "attrs": [], "contents": [], "driver": "basicserver", "name": "testserver2", "parents": [ "/pool/multipool" ] } ] HTTP: 200 Content-type: application/json $ ${get} -d 'name=nonserver1' -d 'name=nonserver2' ${server_url}/by-names [ null, null ] HTTP: 404 Content-type: application/json """ objs = [] names = bottle.request.params.getall('name') if not names: return util.dumps('Provide at least one name to get data from', 412) mode = bottle.request.headers.get('Clusto-Mode', default='compact') for name in names: obj, status, msg = util.get(name) try: objs.append(util.show(obj, mode) if obj else None) except TypeError as te: return util.dumps('%s' % (te,), 409) return util.dumps(objs, 200 if all(objs) else 206 if any(objs) else 404)
def get_by_name(name): """ One of the main ``clusto`` operations. Parameters: * Required path parameter: ``name`` - The name you're looking for * Optional: ``driver`` - If provided, a driver check will be added to ensure the resulting object is the type you're expecting .. note:: This function returns expanded objects by default in order to reduce the amount of required custom headers. Therefore, the header is not required to receive expanded objects. Examples: .. code:: bash $ ${get} ${server_url}/by-name/nonserver "Object \"nonserver\" not found (nonserver does not exist.)" HTTP: 404 Content-type: application/json $ ${get} -H 'Clusto-Mode: compact' ${server_url}/by-name/testserver1 "/basicserver/testserver1" HTTP: 200 Content-type: application/json $ ${get} ${server_url}/by-name/testserver1 { "attrs": [], "contents": [], "driver": "basicserver", "name": "testserver1", "parents": [ "/pool/singlepool", "/pool/multipool" ] } HTTP: 200 Content-type: application/json $ ${get} -d 'driver=pool' ${server_url}/by-name/testserver1 "The driver for object \"testserver1\" is not \"pool\"" HTTP: 409 Content-type: application/json $ ${get} -d 'driver=nondriver' ${server_url}/by-name/testserver1 "The driver \"nondriver\" is not a valid driver" HTTP: 412 Content-type: application/json """ driver = bottle.request.params.get('driver', default=None) mode = bottle.request.headers.get('Clusto-Mode', default='expanded') obj, status, msg = util.get(name, driver) if not obj: return util.dumps(msg, status) try: return util.dumps(util.show(obj, mode)) except TypeError as te: return util.dumps('%s' % (te,), 409)
def get_from_pools(): """ One of the main ``clusto`` operations. Parameters: * Required: at least one ``pool`` parameter * Optional: one or more ``driver`` parameter to filter out results * Optional: one or more ``type`` parameter to filter out results * Optional: a boolean ``children`` parameter to search for children recursively (True by default) Examples: .. code:: bash $ ${get} ${server_url}/from-pools "Provide at least one pool to get data from" HTTP: 412 Content-type: application/json $ ${get} -d 'pool=emptypool' ${server_url}/from-pools [] HTTP: 200 Content-type: application/json $ ${get} -d 'pool=singlepool' -d 'pool=multipool' ${server_url}/from-pools [ "/basicserver/testserver1" ] HTTP: 200 Content-type: application/json $ ${get} -H 'Clusto-Mode: expanded' -d 'pool=multipool' ${server_url}/from-pools [ { "attrs": [], "contents": [], "driver": "basicserver", "name": "testserver1", "parents": [ "/pool/singlepool", "/pool/multipool" ] }, { "attrs": [], "contents": [], "driver": "basicserver", "name": "testserver2", "parents": [ "/pool/multipool" ] } ] HTTP: 200 Content-type: application/json """ pools = bottle.request.params.getall('pool') if not pools: return util.dumps('Provide at least one pool to get data from', 412) types = bottle.request.params.getall('type') drivers = bottle.request.params.getall('driver') children = bottle.request.params.get('children', default=True, type=bool) mode = bottle.request.headers.get('Clusto-Mode', default='compact') current = int(bottle.request.headers.get('Clusto-Page', default='0')) per = int(bottle.request.headers.get('Clusto-Per-Page', default='50')) try: ents = clusto.get_from_pools( pools, clusto_types=types, clusto_drivers=drivers, search_children=children ) results = [] headers = {} if current: ents, total = util.page(list(ents), current=current, per=per) headers = { 'Clusto-Pages': total, 'Clusto-Per-Page': per, 'Clusto-Page': current } for ent in ents: results.append(util.show(ent, mode)) return util.dumps(results, headers=headers) except TypeError as te: return util.dumps('%s' % (te,), 409) except LookupError as le: return util.dumps('%s' % (le,), 404) except Exception as e: return util.dumps('%s' % (e,), 500)
def play_game(path_in, path_is_url=False, printall=False, \ draw_contours=True, resize_contours=True, \ draw_rects=False, sets_or_no=False, \ pop_open=True): """Takes in an image path (to local file or onlin), finds all sets, and pretty prints them to screen. if printall - prints the identities of all cards in the image if draw_contours - outlines the cards belonging to each set if resize_contours - enlarges contours for cards belonging to multiple sets to avoid overlay if draw_rects - draws box rects around cards belonging to each set if sets_or_no - outlines the image in green or red, depending on whether there are any sets present""" if path_is_url: # parse image string directly into numpy array img_str = requests.get(path_in).content nparr = np.fromstring(img_str, np.uint8) img = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR) else: img = cv2.imread(path_in) img = s.resize_image(img, 600) util.show(img) contours, detected = s.detect_cards(img, draw_rects=False, return_contours=True) props = s.get_cards_properties(detected) if printall: s.pretty_print_properties(props) g = game(cards=props) sets = g.play(idx=True) # RED, ORANGE, YELLOW, GREEN, BLUE, //INDIGO,// VIOLET #BGR_RAINBOW = [ (0, 0, 255), (0, 127, 255), (0, 255, 255), \ # (0, 255, 0), (255, 0, 0), #(130, 0, 75), # (255, 0, 139) ] if sets: # choose a group of colors at random to represent the set of sets #COLORS = random.sample(BGR_RAINBOW, len(sets)) COLORS = util.random_color_palette(len(sets)) if resize_contours: # count number of sets that each winning card index belongs to counter = Counter( card[0] for st in sets for card in st ) for i, st in enumerate(sets): color = COLORS[i] st_indices, st_props = zip(*st) s.pretty_print_properties(st_props) print ('---') if draw_contours or draw_rects: winning_contours = [ contours[c] for c in st_indices ] if draw_contours: if resize_contours: for idx in st_indices: # set base thickness thickness = 3 count = counter[idx] if count > 1: thickness += 6*counter[idx] counter[idx] -= 1 cv2.drawContours(img, contours, idx, color, thickness) else: cv2.drawContours(img, winning_contours, -1, color, 3) if draw_rects: # get bounding rectangles winning_rects = [ cv2.minAreaRect(c) for c in winning_contours ] for rect in winning_rects: # convert to ints r = [ (int(x), int(y)) for x,y in cv.BoxPoints(rect) ] cv2.rectangle(img, r[0], r[2], color) else: print 'no sets :(' if sets_or_no: height, width, _ = img.shape BORDER_SCALAR = 0.01 border_h, border_w = ( int(dim*BORDER_SCALAR) for dim in (height, width)) # indices 0 or 1 correspond to bool for if no sets (BGR for red) or sets (green) BORDER_COLORS = [ (19,19,214), (94,214,19) ] img_outlined = cv2.copyMakeBorder(img, border_h, border_h, \ border_w, border_w, \ cv2.BORDER_CONSTANT, value = BORDER_COLORS[bool(sets)]) processed_img = (img_outlined if sets_or_no else img) final_img = processed_img #s.resize_image(processed_img, 800) if pop_open: util.show(final_img) num_sets = ( len(sets) if sets else 0 ) # convert image array to string representing JPEG of image (in RGB) image = Image.fromarray( cv2.cvtColor(processed_img, cv2.COLOR_BGR2RGB) ) output = StringIO.StringIO() image.save(output, format='JPEG') mystr = output.getvalue() output.close() # don't write image to file, dude....because we are badass Tweepy hackers #cv2.imwrite('tmp.jpeg', final_img) # encode image string to base64 and safe-encode it for Twitter upload request final = requests.utils.quote(base64.b64encode(mystr), safe='') #l = len(final) #print 'length is {}'.format(l) #print 'size is {} bytes'.format((l-814)/1.37) # N.B. # length is 123932 # size is 89867.1532847 bytes return (num_sets, final)
###FEATURE IMPORTANCE### from sklearn import ensemble from sklearn import datasets from sklearn.utils import shuffle from sklearn.metrics import mean_squared_error ########################################################################### # Load data boston = datasets.load_boston() X, y = shuffle(boston.data, boston.target, random_state=13) X = X.astype(np.float32) offset = int(X.shape[0] * 0.9) X_train, y_train = X[:offset], y[:offset] X_test, y_test = X[offset:], y[offset:] ############################################################################### # Fit regression model params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 1, 'learn_rate': 0.01, 'loss': 'ls'} clf = ensemble.GradientBoostingRegressor(**params) clf.fit(X_train, y_train) mse = mean_squared_error(y_test, clf.predict(X_test)) print("MSE: %.4f" % mse) ###PLOTIT### plot_feature_importance(boston.feature_names, clf.feature_importances_) ###Show them### show()
def main(): if len(sys.argv) < 3: print('%s: error: invalid arguments' % sys.argv[0], file=sys.stderr) print('usage: %s PATH_TO_IMAGE PATH_TO_PARAMS' % sys.argv[0], file=sys.stderr) return 1 else: filename = sys.argv[1] params_path = sys.argv[2] img = cv2.imread(filename) util.show(filename, img) filename = filename[filename.rfind("/")+1:filename.rfind(".")] params.load(params_path) # find page & correct for perspective img2 = persp.find_page(img) util.show(filename + ' (corrected)', img2, save=True) img3, staff_lines = clean.find_staff_lines(img2) util.debug('found %d staff lines: %s' % (len(staff_lines), str(staff_lines))) util.show(filename + ' (without staff lines)', img3, save=True) objs = segment.find_objects(img3) util.debug('found %d objects: %s' % (len(objs), str(objs))) objs2 = discard.filter_musical_objects(img3, objs) util.debug('remaining %d musical objects: %s' % (len(objs2), str(objs2))) notes_list = notes.find_notes(img3, objs2, staff_lines) util.debug('notes list: ' + str(notes_list)) # create a MIDI file from the notes list midi_file = MIDIFile(numTracks=1) midi_file.addTrackName(0, 0, "Track 0") for i, (pitch, kind) in enumerate(notes_list): freq = midi_note_number(pitch) if kind == 'quarter': beats = 1 elif kind == 'eighth': beats = 0.5 elif kind == 'half': beats = 2 elif kind == 'whole': beats = 4 midi_file.addNote( track=0, channel=0, pitch=int(round(freq)), time=i, duration=beats, volume=100 ) out = open('output.mid', 'wb') midi_file.writeFile(out) out.close() cv2.waitKey(0)
def main(): args = parse_args() syris.init() # Propagate to 20 cm d = 20 * q.cm # Compute grid n_camera = 256 n = n_camera * args.supersampling shape = (n, n) material = get_material('pmma_5_30_kev.mat') energies = material.energies dE = energies[1] - energies[0] # Lens with magnification 5 and numerical aperture 0.25 lens = Lens(5, na=0.25) # Considered visible light wavelengths vis_wavelengths = np.arange(500, 700) * q.nm # Simple camera quantum efficiencies cam_qe = 0.1 * np.ones(len(vis_wavelengths)) camera = Camera(10 * q.um, 0.1, 500, 23, 32, (256, 256), exp_time=args.exposure * q.ms, fps=1 / q.s, quantum_efficiencies=cam_qe, wavelengths=vis_wavelengths, dtype=np.float32) # Scintillator emits visible light into a region given by a Gaussian distribution x = camera.wavelengths.rescale(q.nm).magnitude sigma = fwnm_to_sigma(50) emission = np.exp(-(x - 600) ** 2 / (2 * sigma ** 2)) / (sigma * np.sqrt(2 * np.pi)) # Scintillator 50 um thick, light yield 14 and refractive index 1.84 luag = get_material('luag.mat') scintillator = Scintillator(50 * q.um, luag, 14 * np.ones(len(energies)) / q.keV, energies, emission / q.nm, camera.wavelengths, 1.84) detector = Detector(scintillator, lens, camera) # Pixel size used for propagation ps = detector.pixel_size / args.supersampling fmt = 'Pixel size used for propagation: {}' print fmt.format(ps.rescale(q.um)) fmt = ' Effective detector pixel size: {}' print fmt.format(detector.pixel_size.rescale(q.um)) print ' Field of view: {}'.format(n * ps.rescale(q.um)) # Bending magnet source trajectory = Trajectory([(n / 2, n / 2, 0)] * ps) source = make_topotomo(dE=dE, trajectory=trajectory, pixel_size=ps) sample = make_sphere(n, n / 4. * ps, pixel_size=ps, material=material) # Propagation with a monochromatic plane incident wave coherent = propagate([source, sample], shape, [15 * q.keV], d, ps, t=0 * q.s, detector=detector).get() coherent *= camera.exp_time.simplified.magnitude # Decimate to fit the effective pixel size of the detector system coherent_ld = camera.get_image(coherent, shot_noise=False, amplifier_noise=False) # Propagation which takes into account polychromaticity poly = propagate([source, sample], shape, range(10, 30) * q.keV, d, ps, t=0 * q.s, detector=detector).get() poly *= camera.exp_time.simplified.magnitude poly_ld = camera.get_image(poly, shot_noise=args.noise, amplifier_noise=args.noise) # Compute and show some of the used propagators propagator_10 = get_propagator_psf(n, d, ps, 10 * q.keV) propagator_30 = get_propagator_psf(n, d, ps, 30 * q.keV) show(coherent, title='Coherent Supersampled') show(coherent_ld, title='Coherent Detector') show(propagator_10.real, title='Propagator PSF for 10 keV (real part)') show(propagator_30.real, title='Propagator PSF for 30 keV (real part)') show(poly, title='Polychromatic Supersampled') show(poly_ld, title='Polychromatic Detector') plt.show()