iMaskJS - dynamic mask with multiple possible masks - imaskjs

I am trying to create an input receiving and formatting an Israeli phone number.
In Israel, we have multiple phone number formats, and I wish the input could identify and format the number correctly.
For example, here are a few phone formats here:
Type
Format
Emergency numbers
10X or 11X or 12XX
Geographical
(0A) XXX-XXXX
Cellular and Mobile
05N XXX-XXXX
Non-geographical (VoIP)
07N XXX-XXXX
Business toll
1 700 XXX-XXX
Another business toll
1 599 XXX-XXX
Free toll
1 800 XXX-XXX
I tried using imask js with dynamic masks.
const mask = {
masks: [
{ mask: '{1}{0}0' },
{ mask: '{1}{1}0' },
{ mask: '{1}{2}00' },
{ mask: '{1} {7}{0}{0} 000-000' },
{ mask: '{1} {5}{0}{0} 000-000' },
{ mask: '{1} {8}{0}{0} 000-000' },
{ mask: '{1} {9}{0}{0} 000-000' },
{
mask: '({0}A) 000-0000',
definitions: {
A: /[23489]/
}
},
{
mask: '05N 000-0000',
definitions: {
N: /[012345689]/
}
},
{
mask: '07N 000-0000',
definitions: {
N: /[1234679]/
}
}
]
}
However, when I type any digit in the input, for example 0 to enter a mobile number, it immediately selects the first mask (emergency) and fills in the following number: 100.

Related

Spinning circle with transloadit. Is it possible with watermark or image rotation?

I'm trying to achieve a spinning circle with artwork as a mask.
From what I've seen there is no way to use a moving watermark or an automatic rotation of an image. Is it possible with transloadit?
The result should be a "vinyl" spinning.
This question is quite complex to answer, but it's very much do-able with Transloadit. I'll be using python to answer it primarily for OpenCV, but of course you can use a language that you prefer - I'll try and make it as language agnostic as possible.
I used 4 different templates to get the result we want, as well as some local python magic to tie everything together - here goes.
First we need to resize the image so it fits nicely onto the vinyl record.
{
"steps": {
":original": {
"robot": "/upload/handle"
},
"resize": {
"use": ":original",
"robot": "/image/resize",
"format": "png",
"resize_strategy": "fillcrop",
"width": 350,
"height": 350,
"imagemagick_stack": "v2.0.7"
}
}
}
Now, we want to mask this image using OpenCV and NumPy like so:
# Mask the image
# Reads the input image
img = cv2.imread(img_path)
# Creates a mask with the same size as the image
mask = np.zeros(img.shape, dtype=np.uint8)
# Creates a white circle in the centre
mask = cv2.circle(mask, (175, 175), 175, (255, 255, 255), -1)
# Makes a small whole in the centre of the mask
mask = cv2.circle(mask, (175, 175), 20, (0, 0, 0), -1)
result = cv2.bitwise_and(img, mask)
This will take an image, and create a mask for it that should look like a donut.
Then, using a bitwise and operation between the image and the mask you end up with a cookie cutter of the original image
Yet we still need to remove the black background - which is what we use this template for:
{
"steps": {
":original": {
"robot": "/upload/handle"
},
"trimmed": {
"use": ":original",
"robot": "/image/resize",
"alpha": "Activate",
"type": "TrueColor",
"transparent": "0,0,0",
"imagemagick_stack": "v2.0.7"
}
}
}
This will just make all black pixels transparent.
We can now use Transloadit's watermark feature to overlay this image onto our vinyl record
{
"steps": {
":original": {
"robot": "/upload/handle"
},
"watermark": {
"use": ":original",
"robot": "/image/resize",
"watermark_size": "33%",
"watermark_position": "center",
"imagemagick_stack": "v2.0.7"
}
}
}
Now, all that is left is to make it spin. What we can do is create say 60 frames, and have the image rotate, then using the /video/merge robot - to stitch it all together into a seamless GIF.
{
"steps": {
":original": {
"robot": "/upload/handle"
},
"rotate_image": {
"use": ":original",
"robot": "/image/resize",
"rotation": "${file.basename}",
"resize_strategy": "crop",
"imagemagick_stack": "v2.0.7"
},
"animated": {
"robot": "/video/merge",
"use": {
"steps": [
{
"name": "rotate_image",
"as": "image"
}
],
"bundle_steps": true
},
"result": true,
"ffmpeg_stack": "v4.3.1",
"ffmpeg": {
"f": "gif",
"pix_fmt": "rgb24"
}
}
}
}
Here I use the image's name to determine how many degrees to rotate it by - so when I'm uploading the files to the robot I will name the image based on its index in an array using this python code:
# Now we make a list of images that represent each frame
no_of_frames = 60
assembly = tl.new_assembly({'template_id': [SPINNING_VINYL_TEMPLATE_ID]})
directory = 'Assets/Frames/{image}'.format(image=img_name)
# Length of our animation in seconds
length = 2
for i in range(no_of_frames):
if not os.path.exists(directory):
os.mkdir(directory)
# Creates an image based on the index in the animation
# We pass this to the robot so it knows how many degrees to rotate the image by
location = '{directory}/{index}.png'.format(directory=directory, index=round(i*360/no_of_frames))
cv2.imwrite(location, finished_vinyl)
assembly.add_file(open(location, 'rb'))
This is my end result

TensorFlow Object Detection API - Validation loss increase while mAP increase aswell?

Im trying to retrain a model named: faster_rcnn_inception_resnet_v2_atrous_coco
I have only 1 object which i want to detect, it means I have got 1 class only.
I split my data into train (230 images) and validation (100 images).
After creating csv's and record files, I started to train my model with this config:
# Faster R-CNN with Inception Resnet v2, Atrous version;
# Configured for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.
model {
faster_rcnn {
num_classes: 1
image_resizer {
keep_aspect_ratio_resizer {
min_dimension: 600
max_dimension: 1024
}
}
feature_extractor {
type: 'faster_rcnn_inception_resnet_v2'
first_stage_features_stride: 8
}
first_stage_anchor_generator {
grid_anchor_generator {
scales: [0.25, 0.5, 1.0, 2.0]
aspect_ratios: [0.5, 1.0, 2.0]
height_stride: 8
width_stride: 8
}
}
first_stage_atrous_rate: 2
first_stage_box_predictor_conv_hyperparams {
op: CONV
regularizer {
l2_regularizer {
weight: 0.0
}
}
initializer {
truncated_normal_initializer {
stddev: 0.01
}
}
}
first_stage_nms_score_threshold: 0.0
first_stage_nms_iou_threshold: 0.7
first_stage_max_proposals: 300
first_stage_localization_loss_weight: 2.0
first_stage_objectness_loss_weight: 1.0
initial_crop_size: 17
maxpool_kernel_size: 1
maxpool_stride: 1
second_stage_box_predictor {
mask_rcnn_box_predictor {
use_dropout: false
dropout_keep_probability: 1.0
fc_hyperparams {
op: FC
regularizer {
l2_regularizer {
weight: 0.0
}
}
initializer {
variance_scaling_initializer {
factor: 1.0
uniform: true
mode: FAN_AVG
}
}
}
}
}
second_stage_post_processing {
batch_non_max_suppression {
score_threshold: 0.0
iou_threshold: 0.6
max_detections_per_class: 100
max_total_detections: 100
}
score_converter: SOFTMAX
}
second_stage_localization_loss_weight: 2.0
second_stage_classification_loss_weight: 1.0
}
}
train_config: {
batch_size: 1
optimizer {
momentum_optimizer: {
learning_rate: {
manual_step_learning_rate {
initial_learning_rate: 0.0003
schedule {
step: 900000
learning_rate: .00003
}
schedule {
step: 1200000
learning_rate: .000003
}
}
}
momentum_optimizer_value: 0.9
}
use_moving_average: false
}
gradient_clipping_by_norm: 10.0
fine_tune_checkpoint: "faster_rcnn_inception_resnet_v2_atrous_coco_2018_01_28/model.ckpt"
from_detection_checkpoint: true
# Note: The below line limits the training process to 200K steps, which we
# empirically found to be sufficient enough to train the pets dataset. This
# effectively bypasses the learning rate schedule (the learning rate will
# never decay). Remove the below line to train indefinitely.
num_steps: 200000
data_augmentation_options {
random_horizontal_flip {
}
}
}
train_input_reader: {
tf_record_input_reader {
input_path: "data/train.record"
}
label_map_path: "training/object-detection.pbtxt"
}
eval_config: {
num_examples: 100
eval_interval_secs: 60
# Note: The below line limits the evaluation process to 10 evaluations.
# Remove the below line to evaluate indefinitely.
# max_evals: 10
num_visualizations: 100
}
eval_input_reader: {
tf_record_input_reader {
input_path: "data/test.record"
}
label_map_path: "training/object-detection.pbtxt"
shuffle: false
num_readers: 1
}
Now, when I open Tensorboard I get a nice loss graphs:
Loss Graphs
And as you can see training loss (orange) goes down as expected, while val loss (blue) goes down at the begining and then goes up (probably because of overfitting training data).
So far so good, but when i look at mAP and Recall graphs:
mAP graph
Recall graph
I see mAP goess up as loss goes down, but when loss increase, I would think that mAP will decrease, but it goes up, which i can't understand why.. same for Recall graphs..
My val loss is incresing, but mAP & Recall keep increasing aswell, any idea why?

How to add objectpicker and Camera to my entity in Qt3D?

I need to render some lines and points that hold some data in a 3d scene.
And points need to be picked by mouse, and then get the data in the point.
I first try to define a class inherited from QQuickFramebufferObject, however i find it is difficult to do mouse picking.
I find that it has the ObjectPicker in Qt3D module, so i want to use Qt3D to deal with my work.
My test code below. I defined my GeometryRenderer Object, and set vertices data(just draw two triangles). Like this:
GeometryRenderer {
id: geometry
geometry: Geometry {
boundingVolumePositionAttribute: position
Attribute {
id: position
attributeType: Attribute.VertexAttribute
vertexBaseType: Attribute.Float
vertexSize: 3
count: 4
byteOffset: 0
byteStride: 6 * 4
name: "position"
buffer: vertexBuffer
}
Attribute {
id: color
attributeType: Attribute.VertexAttribute
vertexBaseType: Attribute.Float
vertexSize: 3
count: 4
byteOffset: 3 * 4
byteStride: 6 * 4
name: "color"
buffer: vertexBuffer
}
Attribute {
attributeType: Attribute.IndexAttribute
vertexBaseType: Attribute.UnsignedShort
vertexSize: 1
count: 6
buffer: indexBuffer
}
}
Buffer {
id: vertexBuffer
type: Buffer.VertexBuffer
data: new Float32Array(...)
}
Buffer {
id: indexBuffer
type: Buffer.IndexBuffer
data: new Uint16Array(...)
}
}
And then define a material object like this:
Material {
id: material
effect: Effect {
techniques: Technique {
graphicsApiFilter {
profile: GraphicsApiFilter.CoreProfile
}
renderPasses: RenderPass {
shaderProgram: ShaderProgram {
vertexShaderCode: loadSource("qrc:/shader/hellotriangle.vert")
fragmentShaderCode: loadSource("qrc:/shader/hellotriangle.frag")
}
}
}
}
}
And then in my root Entity:
Entity {
id: root
components: [
RenderSettings {
activeFrameGraph: colorBuffer
pickingSettings.pickMethod: PickingSettings.TrianglePicking
pickingSettings.pickResultMode: PickingSettings.NearestPick
},
InputSettings { }
]
ClearBuffers {
id: colorBuffer
clearColor: Qt.rgba(0.8, 0.8, 0.8, 0.6)
buffers: ClearBuffers.ColorDepthBuffer
RenderSurfaceSelector {
RenderStateSet {
renderStates: DepthTest {
depthFunction: DepthTest.Less
}
}
}
}
}
It works, rendering two triangle. And I want to add Qt3D Camera and ObjectPicker in my scene, How can i make it?
I find that if i use ForwardRenderer(but i couldn't find a way to render my own lines/points vertices) instead of ClearBuffers, the Camera and ObjectPicker works

Image atlas in QML

I have an image like this one:
http://www.imagemagick.org/Usage/basics/result.gif
(it contains two rows of individual data: three square images in the upper row, and below another square and two 'empty' squares)
I want to use it inside a repeater, so that I get four image buttons, each with one of the subimages.
Is there a "texture-atlas" modules in QML?
I only found http://doc.qt.io/qt-5/qml-qtquick-sprite.html and I hope there is something that is better for my use-case.
As I said in comment I would do that using QQuickImageProvider since that's the fastest and the least memory intensive way. But QML is very flexible and you can do with it whatever you want. As for your question you can do as following:
Tile.qml
import QtQuick 2.9
Item {
id: container
property alias source: img.source
property int cellWidth: 1
property int cellHeight: 1
property int slideIndex: 0
clip: true
Image {
id: img
property int cols: img.paintedWidth / container.cellWidth
property int rows: img.paintedHeight / container.cellHeight
x: -container.cellWidth * Math.floor(container.slideIndex % cols)
y: -container.cellHeight * Math.floor(container.slideIndex / cols)
}
}
and usage:
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
id: window
title: "Test"
visible: true
width: 600
height: 400
Row {
spacing: 10
anchors.centerIn: parent
Repeater {
model: 4
Tile {
width: 32
height: 32
cellWidth: 32
cellHeight: 32
slideIndex: index
source: "http://www.imagemagick.org/Usage/basics/result.gif"
}
}
}
}
The idea is to wrap the entire image into a container and clip it appropriately. Here I use index-based access to a slide, you can do that as you want.

How to show scatter plot on specific condition which I set using dc.js

I want a scatter plot composed with a line chart, but I only want the scatter plot to show when the value is not zero.
I have data as below, range of val1 is 0~100, range of val2 is -1, 0, 1
[
{
val1: 10,
val2: 0
},
{
val1: 20,
val2: 1
},
{
val1: 30,
val2: -1
},
{
val1: 40,
val2: -1
},
{
val1: 50,
val2: 1
},
{
val1: 60,
val2: 0
},
{
val1: 70,
val2: 0
},
{
val1: 80,
val2: 1
},
{
val1: 90,
val2: 1
},
{
val1: 100,
val2: 1
}
]
I want to show the line chart of val1 every tick and I want to put a scatter plot on top of this line when val2 is -1 or 1, not 0. The scatter plot should be colored by the value.
How can I do it?
This is another of those places where a "fake group" can come in handy, because we're both transforming a group (by coloring the dots), and omitting some points.
(Despite the ugly name for this pattern, it's quite powerful to do live transformations of the data after it's been aggregated, and this technique will probably shape future versions of dc.js.)
Crossfilter on indices
First though, we have to use another unusual technique in order to deal with this data, which has no field which corresponds to the X axis. This may or may not come up in your actual data.
We'll define the crossfilter data as the range of indices within the data, and the dimension key as the index:
var ndx = crossfilter(d3.range(experiments.length)),
dim = ndx.dimension(function(i) { return i; }),
Now whenever we read data, we'll need to use the index to read the original array. So the first group (for the line chart) can be defined like this:
group1 = dim.group().reduceSum(function(i) { return experiments[i].val1; });
Transforming and filtering
Now we get to the heart of the question: how to produce another group which has colored dots for the non-zero val2 values.
Following the "fake group" pattern, we'll create a function which, given a group, produces a new object with a .all() method. The method pulls the data from the first group and transforms it.
function keep_nonzeros(group, field2) {
return {
all: function() {
return group.all().map(function(kv) {
return {
key: kv.key,
value: {
y: kv.value,
color: experiments[kv.key][field2]
}
}
}).filter(function(kv) {
return kv.value.color != 0
})
}
}
}
I chose to first transform the data by adding the color field to the value with .map(), and then filter out the zeros with .filter(). Most "fake groups" use one or both of these handy Array methods.
Building the composite
Now we can build a composite chart using a line chart and a scatter plot:
chart
.width(600)
.height(400)
.x(d3.scale.linear())
.xAxisPadding(0.25).yAxisPadding(5)
.elasticX(true)
.compose([
dc.lineChart(chart).group(group1),
dc.scatterPlot(chart).group(keep_nonzeros(group1, 'val2'))
// https://github.com/dc-js/dc.js/issues/870
.keyAccessor(function(kv) { return kv.key; })
.valueAccessor(function(kv) { return kv.value.y; })
.colorAccessor(function(kv) { return kv.value.color; })
.colors(d3.scale.ordinal().domain([-1,1]).range(['red', 'black']))
]);
Most of this is boilerplate stuff at this point, but note that we have to set both the key and value accessors for the scatterPlot, because it makes unusual assumptions about the key structure which only matter if you want to do rectangular brushing.
Fiddle: https://jsfiddle.net/gordonwoodhull/6cm8bpym/17/

Resources