Trending March 2024 # Fabricjs � � How To Check If A Polygon Object Intersects With Another Object # Suggested April 2024 # Top 8 Popular

You are reading the article Fabricjs � � How To Check If A Polygon Object Intersects With Another Object updated in March 2024 on the website Moimoishop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested April 2024 Fabricjs � � How To Check If A Polygon Object Intersects With Another Object

We can create a Polygon object by creating an instance of fabric.Polygon. A polygon object can be characterized by any closed shape consisting of a set of connected straight line segments. Since it is one of the basic elements of FabricJS, we can also easily customize it by applying properties like angle, opacity etc.

In order to check if a Polygon object intersects with another object, we use the intersectsWithObject method. This method checks whether the object that is passed to it, intersects with the polygon object.

Syntax intersectsWithObject(other: Object, absolute: Boolean, calculate: Boolean ): Boolean Parameters

other − This parameter accepts an Object which specifies the object we want to test.

absolute (optional) − This parameter accepts a String value which specifies whether to use coordinates without viewportTransform or not. This parameter is optional.

Calculate (optional) − This parameter accepts a Boolean value which specifies whether to use coordinates of current position. This parameter is optional.

Example 1: Using intersectsWithObject Method

Let’s see a code example to see the logged output when the intersectsWithObject method is used. The intersectsWithObject method returns true or false on checking if the polygon object intersects with another object. Here, we have initialized two rectangle objects namely rectangleRed and rectangleBlue. Since our polygon object intersects with rectangleRed, a true value is returned.

var canvas = new fabric.Canvas(“canvas”); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250);

var polygon = new fabric.Polygon( [ { x: -20, y: -35 }, { x: 20, y: -35 }, { x: 40, y: 0 }, { x: 20, y: 35 }, { x: -20, y: 35 }, { x: -40, y: 0 }, ], { stroke: “red”, left: 100, top: 10, fill: “black”, strokeWidth: 2, strokeLineJoin: “bevil”, } );

var rectangleRed = new fabric.Rect({ width: 60, height: 20, top: 40, left: 80, fill: “red”, strokeWidth: 6, });

var rectangleBlue = new fabric.Rect({ width: 20, height: 40, top: 70, left: 200, fill: “blue”, });

canvas.add(polygon); canvas.add(rectangleRed); canvas.add(rectangleBlue);

console.log( “Does the polygon object intersect with rectangleRed?: “, polygon.intersectsWithObject(rectangleRed) ); console.log( “Does the polygon object intersect with rectangleBlue?: “, polygon.intersectsWithObject(rectangleBlue) );

Example 2: Using intersectsWithObject Method with Different Objects

In this example, we have used the intersectsWithObject method along with different objects to prove that this method can work with any object.

var canvas = new fabric.Canvas(“canvas”); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250);

var polygon = new fabric.Polygon( [ { x: -20, y: -35 }, { x: 20, y: -35 }, { x: 40, y: 0 }, { x: 20, y: 35 }, { x: -20, y: 35 }, { x: -40, y: 0 }, ], { stroke: “red”, left: 100, top: 10, fill: “black”, strokeWidth: 2, strokeLineJoin: “bevil”, } );

var triangle = new fabric.Triangle({ width: 90, height: 70, top: 40, left: 80, fill: “red”, strokeWidth: 6, });

var circle = new fabric.Circle({ radius: 40, top: 70, left: 200, fill: “blue”, });

canvas.add(polygon); canvas.add(triangle); canvas.add(circle);

console.log( “Does the polygon object intersect with triangle?: “, polygon.intersectsWithObject(triangle) ); console.log( “Does the polygon object intersect with circle?: “, polygon.intersectsWithObject(circle) );

Conclusion

In this tutorial, we used two examples to demonstrate how you can check if a Polygon object intersects with another object using FabricJS.

You're reading Fabricjs � � How To Check If A Polygon Object Intersects With Another Object

How To Straighten An Itext Object Using Fabricjs?

In this tutorial, we are going to learn about how to straighten an IText object using FabricJS. The IText class was introduced in FabricJS version 1.4, extends chúng tôi and is used to create IText instances. An IText instance gives us the freedom to select, cut, paste or add new text without additional configurations. There are also various supported key combinations and mouse/touch combinations which make text interactive which are not provided in Text.

Textbox, however, which is based on IText allows us to resize the text rectangle and wraps lines automatically. This is not true for IText as height is not adjusted based on the wrapping of lines. We can manipulate our IText object by using various properties. Likewise, we can straighten an IText object by using the straighten method.

Syntax straighten(): fabric.Object Example 1

Passing the angle property a value without using the straighten method

Let’s see a code example to see how our IText object looks when the straighten method is not used. The straighten method straightens an object by rotating it from its current angle to 0,90,180 or 270 etc., depending on the angle that is closer. The angle property sets the angle of rotation of an object in degrees. Here, we have specified the angle as 45. But since we have not applied the straighten property, the angle of rotation will remain as 45 degrees.

var

canvas

=

new

fabric

.

Canvas

(

“canvas”

)

;

canvas

.

setWidth

(

document

.

body

.

scrollWidth

)

;

canvas

.

setHeight

(

250

)

;

width

:

300

,

left

:

210

,

top

:

70

,

fontSize

:

30

,

fill

:

“#b666d2”

,

backgroundColor

:

“#f8f4ff”

,

angle

:

45

,

}

)

;

canvas

.

add

(

itext

)

;

Example 2

Using the straighten method

Let’s see a code example to see how the IText object looks like when the straighten method is used in conjunction with the angle property. Although we have set the angle of rotation as 45 degrees, our itext object will be straightened by rotating it back to 0 degree as we have used the straighten method.

var

canvas

=

new

fabric

.

Canvas

(

“canvas”

)

;

canvas

.

setWidth

(

document

.

body

.

scrollWidth

)

;

canvas

.

setHeight

(

250

)

;

width

:

300

,

left

:

210

,

top

:

70

,

fontSize

:

30

,

fill

:

“#b666d2”

,

backgroundColor

:

“#f8f4ff”

,

angle

:

45

,

}

)

;

canvas

.

add

(

itext

)

;

itext

.

straighten

(

)

;

What Is Smart Object? How To Use Smart Object In Photoshop?

What is Photoshop Smart Object?

Photoshop Smart Object is never let lose the quality of any vector object or an image, even if we rescale or resample it or change its position or rotate it however we want in our document.

Every designer must know about the benefit of “smart object”.

Means you bring any photographs or any vector objects in your document and you scale it down and scale it up again. In this process of scaling up and down the image, if you do not want to lose real quality of your image then you must make that image a “ smartobject” first

Let’s see an example so that you can get the actual idea of “smart object”.

Here I have a vector object in illustrator.

I copy this object by pressing CTRL + C. then go to photoshop and press CTRL + V to paste.

When I paste it on photoshop it gives 4 different options to choose such like “smart object”, ”pixel”, ”path” & “shape layer”.

This time I’m going to select photoshop smart objects.

Press ok.

So here is our vector object with good quality.

See there in layer panel the layer have a small icon on bottom corner of it. this small icon indicates this is a smart object.

Now press CTRL + T and scale down the object.

Press CTRL + T again and scale it up and hit enter.

You can see here that the quality and sharpness of the object is as much as before we scale it down. it haven’t lose even 1% of quality.

Now switch of this layer and press CTRL + V to paste it again.

But this time I’m going to select pixels.

The object is in it’s original quality now.

But once we scale it down and scale it up again, you can see how it is losing the real quality of the object. it has been blurred and loss too much color information of the object.

Let’s see the reason, why the object haven’t lose its information when it is converted to smart object and why it lost them all when it was a normal layer.

Take the smart object layer and scale it down and rescale it up.

You can see it don’t lose any color information and remains sharp and that’s because it’s embedded inside of the smart object which means it is referring to original vector information instead of referring pixel information when it was imported.

And now let’s talk about the object which we have imported as pixel.

When we scale it down it doesn’t need much information to display at this smaller size, so it throws away extra information which are not needed to display.

Now when we are scaling it back up it don’t remember that extra information to which it have thrown away before, when we have scaled it down. so you can see how it have lost its quality and sharpness and how bad it looks.

If you are a designer and you are working on composite design in photoshop, and you are using different objects in your work and you are rescaling, resampling, rotating and repositioning them to get the right look it will going to definitely decrease the real quality of the images if all are not converted to “smart object”.

How To Print Content Of Javascript Object?

In this tutorial, we will learn to print the content of a JavaScript object.

Objects are similar to variables, but they can contain many values. Javascript object values are written as key: value pairs, and each pair is separated by commas. It is used to access data from databases or any other sources.

Following are the ways to print the content of JavaScript objects −

Using the JSON.stringify() Method

And using a for-in loop

Using Object.values()

Using the JSON.stringify() Method

The JSON.stringify() is used to convert JavaScript Objects into a string. We have to use JSON.stringify() to send the data to the server. Arrays can also be converted to the string by using JSON.stringify().

Syntax

Following is the syntax to print the content of JavaScript objects by using JSON.stringify() −

var obj = {}; JSON.stringify(obj); Parameters

obj − Name of an Object

Example

In the below given example, we are using the JSON.stringify() method to print the content of a JavaScript object

const

Student

=

{

name

:

“Akshay”

,

age

:

18

,

percentage

:

95.45

}

;

const

print

=

JSON

.

stringify

(

Student

)

;

var

message

=

“Content of Javascript object:”

;

In the above example, users can see that we have printed the content of a JavaScript object using the JSON.stringify method.

Using the Object.values() Method

Object.values() is the method used to convert a javascript object into an array. Object.values() takes an Object as a parameter and outputs object values as elements of an array.

Syntax

Following is the syntax to print the content of a JavaScript object −

var obj = {}; Object.values(obj); Parameters

obj − Name of an Object

Example

In the below given example, we are using the Object.values() method to print the content of a JavaScript object.

const

Student

=

{

name

:

“Akshay”

,

age

:

18

,

percentage

:

95.45

}

;

const

value

=

Object

.

values

(

Student

)

;

var

message

=

“Content of Javascript object:”

;

In the above example, users can see that we have printed the content of a JavaScript object using the Object.Values() method.

Using a for-in loop to print the content of a JavaScript object

To execute a block of statements for every property of an object, a for-in loop is used.

Users can follow the below syntax to print the content of JavaScript objects by using the for-in loop −

Syntax var object = {}; for (key in object) { } Parameters

key − A Name of the property of an object (You can use any user-defined variable)

object − A Name of an object to print

Example

In the below given example, we are using the for-in loop to print the content of a JavaScript object.

const

Student

=

{

name

:

“Akshay”

,

age

:

18

,

percentage

:

95.45

}

;

let

value

=

“”

;

for

(

let

key

in

Student

)

{

}

;

var

message

=

“Content of JavaScript object:”

;

In the above example, users can see that we have printed the content of a JavaScript object using the for-in loop.

We have learned to print the content of a JavaScript Object. Among the above three ways, the JSON.stringify() method prints both keys and their values, whereas the other two ways only print the values of the properties. JSON.stringify() is the most used method for exchanging the data between the client and the server.

A Beginner’s Guide To Focal Loss In Object Detection!

Introduction

Object detection is one of the most widely studied topics in the computer vision community. It’s has been breaking into various industries with use cases from image security, surveillance, automated vehicle systems to machine inspection.

Currently, deep learning-based object detection can be majorly classified into two groups:-

Two-stage detectors, such as Region-based CNN (R-CNN) and its successors.

and, One-stage detectors, such as the YOLO family of detectors and SSD

One-stage detectors that are applied over a regular, dense sampling of anchor boxes (possible object locations) have the potential to be faster and simpler but have trailed the accuracy of two-stage detectors because of extreme class imbalance encountered during training.

FAIR has released a paper in 2023, in which they introduced the concept of Focal loss to handle this class imbalance problem with their one stage detector called RetinaNet.

Before we deep dive into the nitty-gritty of Focal loss, let’s First, understand what is this class imbalance problem and the possible problems caused by it.

Why Focal Loss Needed

What is Focal Loss

Cross-Entropy Loss

Problem with Cross-Entropy

Examples

Balanced Cross-Entropy

Problem with Balanced Cross-Entropy

Examples

Focal loss explanation

Examples

Cross-Entropy vs Focal Loss

Easily correctly classified records

Misclassified records

Very easily classified records

Final Thoughts

Why Focal Loss Needed?

This imbalance causes two problems –

Training is inefficient as most locations are easy negatives (meaning that they can be easily classified by the detector as background) that contribute no useful learning.

Since easy negatives (detections with high probabilities) account for a large portion of inputs. Although they result in small loss values individually but collectively, they can overwhelm the loss & computed gradients and can lead to degenerated models.

What is Focal Loss?

In simple words, Focal Loss (FL) is an improved version of Cross-Entropy Loss (CE)  that tries to handle the class imbalance problem by assigning more weights to hard or easily misclassified examples  (i.e. background with noisy texture or partial object or the object of our interest ) and to down-weight easy examples (i.e. Background objects).

So Focal Loss reduces the loss contribution from easy examples and increases the importance of correcting misclassified examples.)

So, let’s first understand what Cross-Entropy loss for binary classification.

The idea behind Cross-Entropy loss is to penalize the wrong predictions more than to reward the right predictions.

Cross entropy loss for binary classification is written as follows-

Where –

Yact = Actual Value of Y

Ypred =  Predicted Value of Y

For Notational convenience, let’s write Ypred  as p & Yact as Y.

Y ∈ {0,1}, It’s the ground truth class

p ∈ [0,1], is the model’s estimated probability for the class with Y=1.

For notational convenience, we can rewrite the above equation as –

pt = {-ln(p)         , when Y=1 -ln(1-p)    ,when Y=}

CE (p, y) = CE (pt)=-ln⁡(pt)

Fig: – The focal loss down weights easy examples with a factor of  (1-  pt)γ

Let’s understand it using an example below-

Examples: –

CE(FG) = -ln (0.95) =0.05

CE(BG)=-ln (1- 0.05) =0.05

A common approach to addressing such a class imbalance problem is to introduce a weighting factor ∝∈[0,1] for class 1 & 1- for class -1.

For notational convenience, we can define ∝t in loss function as follows-

CE (pt )= -∝tln ln( pt )

As you can see, this is just an extension to Cross-Entropy.

Problem with Balanced Cross-Entropy: –

As our experiments will show, the large class imbalance encountered during the training of dense detectors overwhelms the cross-entropy loss.

Easily classified negatives comprise the majority of the loss and dominate the gradient. While balances the importance of positive/negative examples, it does not differentiate between easy/hard examples.

Let’s understand this with an example-

Examples: –

CE(FG) = -0.25*ln (0.95) =0.0128

CE(BG)=-(1-0.25) * ln (1- 0.05) =0.038

While it does a good job differentiating positive & negative classes correctly but still does not differentiate between easy/hard examples.

And that’s where Focal loss (extension to cross-entropy) comes to rescue.

Focal loss explanation

Focal loss is just an extension of the cross-entropy loss function that would down-weight easy examples and focus training on hard negatives.

(1-  pt)γ  to the cross-entropy loss, with a tunable focusing parameter γ≥0.

RetinaNet object detection method uses an α-balanced variant of the focal loss, where α=0.25, γ=2 works the best.

So focal loss can be defined as –

FL (pt) = -αt(1-  pt)γ log  log(pt).

The focal loss is visualized for several values of γ∈[0,5], refer Figure 1.

We shall note the following properties of the focal loss-

When an example is misclassified and pt is small, the modulating factor is near 1 and the loss is unaffected.

pt→  1, the factor goes to 0 and the loss for well-classified examples is down weighed.

γ smoothly adjusts the rate at which easy examples are down-weighted.

As is increased, the effect of modulating factor is likewise increased. (After a lot of experiments and trials, researchers have found γ = 2 to work best)

Note:- when γ =0, FL is equivalent to CE. Shown blue curve in Fig

Intuitively, the modulating factor reduces the loss contribution from easy examples and extends the range in which an example receives the low loss.

Let’s understand the above properties of focal loss using an example-

Examples: –

When record (either foreground or background) is correctly classified-

Modulating factor (BG)= (1-(1-0.01))2 = 0.0001As you can see, the modulating factor is close to 0, in turn, the loss would be down-weighted.

Modulating factor (BG)= (1-(1-0.99))2 =0.9801As you can see, the modulating factor is close to 1, in turn, the loss is unaffected.

Now let’s compare Cross-Entropy and Focal loss using a few examples and see the impact of focal loss in the training process.

Let’s see the comparison by considering a few scenarios below-

FL(BG)=-0.75 * (1-(1-0.05))2 *ln (1-0.05) =9.61E-5

FL(BG)= -0.75 * (1-(1-0.95))2 *ln (1-0.95) =2.027736282661858  

FL(BG)= -0.75 * (1-(1-0.01))2 *ln (1-0.01) =7.5377518901261E-7

scenario-3: 0.01/0.00000025 = 40,000 times smaller number.

These three cases clearly explain how Focal loss adds down weights the well-classified records and on the other hand, assigns large weight to misclassified or hard classified records.

After a lot of trials and experiments, researchers have found ∝=0.25 & γ=2 to work best.

If you enjoyed this article, leave a few claps, it will encourage me to explore more machine learning techniques & pen them down 🙂

Happy learning. Cheers!!

References: – About the Author

Praveen Kumar Anwla

I’ve been working as a Data Scientist with product-based and Big 4 Audit firms for almost 5 years now. I have been working on various NLP, Machine learning & cutting edge deep learning frameworks to solve business problems. Please feel free to check out my personal blog, where I cover topics from Machine learning – AI, Chatbots to Visualization tools ( Tableau, QlikView, etc.) & various cloud platforms like Azure, IBM & AWS cloud.

Related

What Is A Nan Property Of A Number Object In Javascript?

In JavaScript, the NaN property is a special value that represents “Not a Number”. It is a property of the Number object and can be accessed using Number.NaN.

The NaN property is usually produced as a result of an operation that cannot produce a meaningful result. For example, dividing 0 by 0 or trying to parse an invalid number will both produce NaN.

Here are a few examples of operations that will produce NaN −

Math.sqrt(-1); 0/0; parseInt("foo");

It is important to note that NaN is not equal to any value, including itself. So, if you want to check if a value is NaN, you cannot use the == or === operators. Instead, you should use the isNaN() function, which is designed specifically for this purpose.

Here’s an example of how to use isNaN() −

if (isNaN(someValue)) { console.log("someValue is Not a Number"); } Syntax

Following is the syntax to represent a not a umber −

NaN Number.NaN

We can call NaN from the Number objects, so even NaN represents Not a Number but a Property of a Number object.

Sometimes it is strictly required to pass a number for an operation, in that case, we can throw a NaN error to show the users that they can enter only the Number value.

Example

You can try to run the following example to learn how to use NaN −

function showValue() { var dayOfMonth = 50; dayOfMonth = Number.NaN alert(“Day of Month must be between 1 and 31.”) } Document.write(“Value of dayOfMonth : ” + dayOfMonth ); }

Example

Let’s create a function, sum which takes two parameters and converts them into Integers so that if users enter a Number in decimal or a Number in a string it will automatically change it into integers and sum those integers and print the value. Then we will call the function by passing some arguments.

function sum(a, b) { x = parseInt(a); y = parseInt(b); result = x + y; return result; } let outputDiv = document.getElementById(“output”);

Here when we either pass an Integer or a string containing Integers or Integers in the decimal value we will get the same results because all of the values can be parsed in integers and can be valid numbers but when we pass a string of alphabets we will get an error NaN, which means the value we passed is Not a Number.

Example

Let’s modify the above function, and we want this function to not allow the integers in decimal or even in the string, if the function gets a value that is strictly not a number type then we will console log the NaN to show a message that the entered number is not a number.

function sum(a, b) { if (typeof (a) === “number” && typeof (b) === “number”) { document.write(a + b); } else { document.write(NaN); } } sum(“2”, 4);

JavaScript can convert the numbers from one form to another by itself if it falls under the category of a number, it is not able to convert them into another required form, i.e., the entered number is not a number type in JavaScript, so JavaScript returns an error, NaN, it means not a number. The cool part is that the NaN is also an object of Number which we can access using the chúng tôi property. We can also manually throw the error NaN by using the chúng tôi property or directly passing NaN.

Update the detailed information about Fabricjs � � How To Check If A Polygon Object Intersects With Another Object on the Moimoishop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!