You are reading the article How Does Opencv Findcontour() Work updated in February 2024 on the website Flu.edu.vn. 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 March 2024 How Does Opencv Findcontour() WorkIntroduction to OpenCV findContours
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
It works essentially well on binary pictures and images, thought at the first application of Sobel edges and thresholding techniques should be implemented. Each of the individual contour is representative of an individual numpy array with coordinates x and y, which represents the boundary point for the object that the user has entered.
Syntax of OpenCV findContour()
Following is the syntax used for application of the OpenCV findContour method:void cv :: findContours (InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset = Point() ) Parameters of OpenCV findContour():
Following are the parameters used for the Open CV findContour() method:
Image It is the source image that is used which is generated through a single channel of about eight bits. Any pixels that are in the non-zero category designated as 1’s, the pixels with zero categories are designated as 0’s, perforce converting the image into a binary form. Various parameters (such as adaptiveThreshold, inRange, Canny, threshold, etc.) can then be further applied in order to create the binary images using the coloured or grayscale image that is the user. In case the mode is equal to RETR_FLOODFILL or RETR_CCOMP, then the image which is being entered by the user as the source image be a 3- bit integer-based image of label CV_32SC1.
Contours Detection of contour – each of the single contour has been stored in the form of multiple points that are vectors.
Mode Mode activated specifically to contour retrieval.
Method Mode activated specifically to depict the approximation method for the image contour.
Offset It is an optional parameter by using which every contour point can be shifted. It is essentially useful when the contour has been extracted are image ROI, and then further analysis should be done in the context of the whole image.How does OpenCV findContour() Work?
When the computer is made to detect the edges of an input image, it then finds the points where specifically, there is a significant difference notice in the intensity of colouration, then simply those pixels are turned on. A stark differences noticed when the system is instructed to perform contouring.
Contours are basically an abstract collection of segments and points that correspond to the reflective shapes of the objects that are present in the images that have been processed through the system. as a result of this; it is in our capacity to manipulate the contouring within the programs through which they are being accessed.
This can be done in multiple ways, such as having a count on the number of contours in an image and then using that to categorize the object shapes, for segmentation of images or cropping objects from the image that is being processed and many more such similar functions.Example
Given below is the example of OpenCV findContour:
Code:import numpy as np1 import cv2 img_1 = cv2.imread('EduCBA.png') print (“The Gray scale image is ” /n) imgray_1 = cv2.cvtColor(img_1, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(imgray_1, 127, 255, 0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) print("The Total Number of Contours in the Image = ") print (str(len(contours))) print(contours) cv2.drawContours(img_1, contours, -1,(0,2550,0),3) cv2.drawContours(imgray_1, contours, -1,(0,255,0),3) print (“The original image is: “ /n) cv2.imshow('Image', img_1) cv2.imshow('Image GRAY', imgray_1) cv2.waitKey(0) cv2.destroyAllWindows()
The output screen displays the screenshot on the compiling of the above code.Conclusion – OpenCV findContours
The OpenCV find contour method is essentially useful as it provides for a pre-defined function that can be called without implementation of an entire code and can be modified using the various parameters. It is essentially helpful in terms of analysing the shape of the image provided, in the detection of the size and dimension of the object that has to be detected in the provided image and in the detection of specific objects. This is done in order to categorize the object shapes, for segmentation of images or cropping objects from the image that is being processed and many more such similar functions.Recommended Articles
We hope that this EDUCBA information on “OpenCV findContours” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
You're reading How Does Opencv Findcontour() Work
Code injection, often referred to as remote code execution (RCE), is an attack perpetrated by an attackers ability to inject and execute malicious code into an application; an injection attack. This foreign code is capable of breaching data security, compromising database integrity or private properties. In many instances, it can bypass authentication control, and usually these attacks are associated with applications that depend on user input for execution.
Generally, applications are more vulnerable if the code is executed without first passing through validation. A simple case of a vulnerable code is shown below.
Due to the fact that user interaction with applications is more and more a necessity in today’s online world, code injection has grown and has become a real threat to many online resources.Types of code injections
There are mainly four types of code injections: SQL injection, Script injection, Shell injection, and Dynamic evaluation. All of these have the same working principle, that is, the code is introduced into and executed by applications, but the two I will pay focus on are SQL injection and Script injection.How SQL injections work
In the case of SQL injection, the attack is aimed at corrupting a legitimate database query to produce falsified data. The attacker first has to locate an input within the targeted web application that is included inside of an SQL query.
This method is only effective if the web application has user input included within an SQL statement. A payload (a malicious SQL statement) can then be inserted and run against the database server.
The following server-side pseudo-code is a simple example of authentication that can prove vulnerable to SQL injections.
In the above code the attacker could insert a payload that would change the SQL statement executed by the database server. An example would set the password field to:
This automatically causes the following statement to be run against the database server:
1What SQL injection can do
This is the most common type of code injection. Considering the fact that SQL is the language used to manipulate data stored in Relational Database Management Systems (RDBMS), an attack with the power to give and execute SQL statements can be used to access, modify and even delete data.
It can give the attacker the ability to bypass authentication, have full disclosure of data stored in the database, compromise data integrity and cause repudiation issues, altering balances and voiding transactions.How to prevent SQL injections
There are a few steps to make your applications less vulnerable, but before any of these steps, it is best to assume all user-submitted data is evil and to trust no one. Then you could consider the following:
Disable the use of dynamic SQL – this means don’t construct database queries with user input. If required, sanitize, validate and escape values before making a query with user input data.
Make use of a firewall – A web application firewall (software or application based) will help filter malicious data.
Purchase better software – This simply means coders will be responsible for checking and fixing flaws.
Encrypt or hash passwords and every other confidential data you have, this should include connection strings.
Avoid connecting to your database with admin privileged accounts unless you absolutely need to.Script injection How to prevent script injections
The steps to prevent script injections are dependent on the programming code you are using. Generally, you will want to:
validate and sanitize user input (any form of input fields) by striping out or escaping potentially malicious content
clean up query strings in URLs
validate and sanitize all forms of data, arrays and objects before executing in the serverConclusion
Simply said, prevention is better than a cure. With new updates in technology, there are more threats our systems are going to be exposed to. To stay on top of things, it’s important to have the latest patches and updates and to keep an ear out for best practices. This makes it harder to fall victim to these malicious attacks.
Afam is a writer with a passion for technology amongst many other fields. Aside from putting pen to paper, he is a passionate soccer lover, a dog breeder and enjoys playing the guitar and piano.
Subscribe to our newsletter!
Our latest tutorials delivered straight to your inbox
Sign up for all newsletters.
Introduction to Linux Join
In a certain situation in today’s world, when the data is sparse, it becomes necessary to join 2 files that contain parts of the same data. In other words, using join, one can achieve the utility of “joining” 2 files so that the join output makes more sense and is complete. There are many applications where the join command finds its use. Let us make it more clear to you with an example. Suppose there are 2 files; in one file, we have a list of employees, and in the other, their addresses. Join in Linux comes in handy for these kinds of join situations!
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
The basic syntax attached to the join is:join [OPTION]… FILE1 FILE2
Where FILE1 and FILE 2 are the files, where contents are located, and OPTION denotes the various options we would discuss here, which help achieve the desired requirement.
2. -v option: Way to ONLY print non-paired lines.
3. Join custom columns from 2 files
4. -i / –ignore-case option: Case insensitive join
5. –check-order / –nocheck-order: Check for sort through all input lines.
6. –help option: Display of help message.
Syntax:Join --help How does Join Work in Linux?
Join in Linux finds its application in various uses, and in this section, we will look into some of the most used ones during the explanation of each of them; we will take turns explaining the working of each in due course of the section.
The first and foremost is the basic join, where the intent is to join 2 files through a common key; here, the key is also referred to as an index and acts like matching 2 contents on similar grounds. Think of this as a sports tournament, where teams play against each other on some common ground, may it be goals scored in soccer, runs scored in cricket, and so on. Now since only 2 teams can play against each other in contrast to so many teams in the tournament, there are some common rules to judge the winners and runners-up.
Now, with the same analogous situation, the 2 files will be compared, and wherever the index would match, the contents corresponding to the index will be copied along with a gap. Now, one needs to be careful about any gap or empty character in place as they will tend to be concatenated along. In the next one, there might be conditions where the “index” might be missing from any one of the files, and hence the user may choose to add the non-paired ones during the join with the intent that the result file is something like a union of the files and would contain “best of both worlds”.
Also, one must be aware of the act that the join in Linux is case sensitive. In some scenarios, the user would like to neglect the case of the indexes used for joining. Now, obviously, if the index is a number, the case won’t matter, but in case the index is alphabets, the ascii value of small caps in comparison to all caps is different and hence problematic for Linux to join by default. Hence, the user can use -i to make the indexes case-insensitive during the join.
At last, there are other sets of commands which one can access using –help in Linux, should one feel the need to explore more of Linux join.Examples of Linux Join
Given below are the examples mentioned:Example #1
Join with printing all non-paired rows in File 2.
Syntax:join chúng tôi chúng tôi -a 2
Join with printing all non-paired rows in File 1.
Syntax:join chúng tôi chúng tôi -a 1
Join with printing all non-paired rows in File 2:
Join with printing all non-paired rows in File 1:Example #2
Join with printing ONLY non-paired rows in File 2:
Syntax:join chúng tôi chúng tôi -v 2
Join with printing ONLY non-paired rows in File 1:
Syntax:join chúng tôi chúng tôi -v 1
When the order of custom columns is different:join chúng tôi chúng tôi -1 2 -2 1
When the order of the custom column is the same:join chúng tôi chúng tôi -j 2
When the order of custom columns is different:
When the order of the custom column is the same:Example #4
Syntax:join -i chúng tôi file2.txt join --ignore-case chúng tôi file2.txt
When no option is used, the join returns empty!Example #5
No optionjoin -i chúng tôi file2.txt
Using the option of check orderjoin -i --check-order chúng tôi file2.txt
Using the option to not check the order.join -i --nocheck-order chúng tôi file2.txt
When the option “–nocheck-order” is not available, an error is reported if there is unsorted data. However, when the “–nocheck-order” option is used, the error is suppressed, and the unsorted line is simply omitted from the process.Example #6
With the set of examples and explanations to the working of join in Linux, you must be quite used to the usage of the same, and this will enable you to experiment more with other arguments of Linux join.Recommended Articles
We hope that this EDUCBA information on “Linux Join” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Introduction to numpy.mean()
Numpy.mean() is function in Python language which is responsible for calculating the arithmetic mean for the all the elements present in the array entered by the user. Simply put the functions takes the sum of all the individual elements present along the provided axis and divides the summation by the number of individual calculated elements. The axis along which the calculation is made has to be prespecified or else the default value for axes will be taken.
Start Your Free Software Development CourseSyntax and Parameters
The following is the syntax that displays how to implement numpy.mean().
The syntax entered by the user is sent in terms of float * 64 intermediate and there by returns the value for the associated integers corresponding for the mean value.
The parameter used in the Syntax for using numpy.mean()
a *: *array *_ *like *
The array is being entered by the user or prompted to be entered. In case the array entered is not of an integer data type, then the conversion of the form is tried on the data entered.
axis : None *, * *int *, * *tuple * (optional parameter)
The computation of the axis along the elements of the specified array entered by the user is done. By default, the mean of the pre-flattened array is computed. In case the array entered is a tuple, in such a case the mean is computed over various axes of the array.
dtype * *: * *data *– *type *, (parameter is optional)
For the computation of the mean the parameter type is utilized. By default, the float 64data type is used for arrays with integer data sets. In case the data being input is floating it remains the same as the dtype entered.
out : ndarray, (parameter is optional)
keepdims: bool, (parameter is optional)
If the parameter specified is True, the axis or axes which are deduced are kept in the expected result as the dimensions having size one. The option enables the result to be broadcasted correctly in response to the array which has been entered. In case value by default, a parameter is passed then the keepdims parameter would not be passed on to the method-specific for mean with respect to the array and its sub-classes. However, it must be noted that for non-default values passed the keepdims parameter would be applicable to raising exceptions if any.
m : ndarray
If the parameter out=None, then in such a case a new array is returned which contains the mean values. Else, in such cases, the reference values with respect to the elements if retuned.Example to Implementation NumPy.mean()
Below are the examples mentioned:
Code:import numpy as n1 a1 = n1.array([[10,20,30],[30,40,50],[40,50,60]]) print 'The new array entered by the user is:' print a1 print 'Application of the Numpy.mean() function on the array entered:' print n1.mean(a1) print 'Application of the mean() function alongside the axis - 0:' print n1.mean(a1, axis = 0) print ' Application of the mean() function alongside the axis - 1:' print n1.mean(a1, axis = 1)
The following output would be produced for the code specified above:How Does the numpy.mean() Work?
The function scans through the values which are specified in the array which is provided by the user. It firstly tries to flatten the resultant array before the computation of the arithmetic mean on the same. The below diagrammatic systemic representation shows the function actually executes the calculation:
We can use the NumPy mean function to compute the mean value:
As the function for mean travels through various axis or axes provided by the user, it scan through and tries to integrate the arithmetic mean functionality for all integral values, Where the elements do not match up to be integral data type, it tries to convert such numbers.
Here you can see for a single dimensional array with six specified elements, the functions scans each of the elements and then divides the total summation of the elements by the total number of elements present in the array (here 6).
This way for arrays with multiple dimensions all or specified axis is mentioned along which the mean is calculated which is displayed in an array form for more than one-dimensional arrays.Conclusion
The function mean() in NumPy is very useful for calculating the arithmetic average of elements especially in terms of data given in array subsets. This being calculated through manual code impacts the verbosity of the code and thus impacts on the computation time for long codes with large data sets.Recommended Articles
This is a guide to numpy.mean(). Here we discuss the introduction and working of numpy.mean() along with different examples and its code implementation. You may also look at the following articles to learn more –
Introduction to Ansible Fetch
Ansible fetch module is a file-based module, which is intended to work on files. This module is similar to Ansible copy module, but by default works in reverse order, in terms of source and destination. It is one of such modules that you might need on day to day basis while working on administrative or change management tasks on remote target machines. There are many other modules like a copy, template, etc. which works more or less in a similar way, there usability completely depends on the available feature parameters. In this article, we will learn about the Ansible Fetch module by using some examples and details on parameters that are usable under this module.
Start Your Free Software Development Course
Web development, programming languages, Software testing & othersWhat is Ansible Fetch?
This module will treat remote machines as a source of files and local controller machines as a destination.
Fetched files are organized by hostname, in a file tree structure.
Files with different contents but the same name are overwritten on destination.
This module works as it is, for Microsoft Windows machines as well.
It is suggested to not use this module with Ansible to become parameters as this will lead to doubling the size of the transfer file. As checksum will also be calculating. This will then lead to consuming all available memory on remote or local hosts causing MemoryError.
When reading of remote files is not possible, then we shall use fail_whenor ignore_errorsor fail_on_missing, to avoid failure of the playbook.How Does Ansible Fetch Work?
To efficiently use Ansible fetch module, one much learn about all available parameters, their acceptable values. Also, there are some parameters that have default values set always, which will be realized to your playbook even if you do not mention the related parameter in the playbook. So these become more important to know. Below is a list of all available parameters and related acceptable or default values.
dest: This is to set the directory where fetched files will be saved. Point to note that under this directory another directory will be created which is named after the hostname of target remote systems, but based of inventory entries. Under this directory, the whole directory structure as a source will be created and then file will be copied into it.
fail_on_missing: Default is yes. This will cause the playbook failure when Ansible is unable to read files on source systems, reason can be anything like permission, non-existence, etc. Available values are yes and no.
flat: Default is no. Acceptable values are yes and no. This is to set the override the default behavior of the fetch module. Thus to behave in such a way where files will be copied directly to destination location without creating hostname-based directory structure.
src: To give the file name on remote systems to fetch. This must be a filename, not any directory name, as fetching of the directory is not supported yet.
validate_checksum: Default is yes. Acceptable values are yes and no. To verify the source and destination checksum of files after fetching.Examples to Implement Ansible Fetch
In this section, we will learn by doing looking at some examples where we tried to test the functionality of the Ansible reboot module. But we shall know about our lab environment first before moving ahead in this section.
Here we have one Ansible controller node named as ansible-controller. As target nodes, we have two remote machines. First machine is a Red Hat Enterprise Linux machine named as host-one and the second machine is an Ubuntu machine named as host-two. We will run our playbooks on the Ansible controller machine and make changes on remote target machines.Example #1
In this example, we have a playbook that is used to fetch a file from remote target nodes and store on the local Ansible controller machine. Then we will check on the local Ansible controller machine that how the file is stored and what directory tree structure is created for this.
Then running this playbook like below:
# ansible-playbook ansible_fetch.yaml
Now in the output, we can see that files are fetched and stored on Ansible local machine in a directory structure.
Upon checking the directory structure, we found that a full directory structure has been created on the local machine.
Also, check the timestamp of files and directories.Example #2
In this example, we have a playbook that is used to fetch a file from remote target nodes and store on local Ansible controller machine. Here we have used a parameter named flat=yes. This is used to override the default behavior of the Ansible fetch module and copy file as it is with name and under path mentioned in the dest parameter. Then we will check on the local Ansible controller machine that how the file is stored and what directory tree structure is created for this.
Then running this playbook like below: –
# ansible-playbook ansible_fetch_flat.yaml -v
Then stored on Ansible local machine in the same directory with a new name and no new directory structure is created.Conclusion
As we saw in this article, Ansible fetch module is easy to use though a very useful module, which you will definitely need in your Ansible skill set. Also having knowledge of its all available features and possibilities will enable you to use it to full extend. So learn it first and then use it.Recommended Article
This is a guide to Ansible Fetch. Here we discuss What is Ansible Fetch and its syntax along with examples as well as code implementation. You can also go through our other suggested articles to learn more –
Introduction to Hive TimeStamp
Hive timestamps are an interpret to be time-zone less and stored as an offset in UNIX format. It is useful to get the updated information of tables at different internal changes to happen in the table. The hive timestamp format is YEAR-Month-Day-Hours-Minutes-seconds [YYYY-MM-DD HH:MM:SS] with an optional fraction of seconds. Anything else that will come with the above format should be read as a string and converted later.
Start Your Free Data Science Course
Hadoop, Data Science, Statistics & others
In the hive, the timestamp plays a vital role in different applications like transactions to identify the changes or updates on the hive tables.
Note: The hive timestamp is only available with starting Hive 0.8.0 version.
Note: In hive timestamp, we need to use the different timestamp or date function available in the hive and use it as per our requirement.How does TimeStamp Work in Hive?
In the hive timestamp, it has the inbuilt functionality of timestamp, with the help of these predefined functions. We can work on the hive timestamp. It has the functionality to convert the hive timestamp to UNIX time format or form UNIX time format to hive timestamp. All the existing date time user definition functions like a month, day, year, hour, etc. are working with the TIMESTAMP data type.
The hive timestamp support below three conversions:
Integer numeric types: In integer numeric, we can interpret the UNIX timestamp in seconds
Floating-point numeric types: In floating-point numeric, we can interpret the UNIX timestamp in seconds with decimal format or precision
Strings type: In string type, we can interpret the JDBC compliant java.sql.Timestamp format “YYYY-MM-DD HH:MM: SS.fffffffff”. it considers 9 decimal place precision.
Note: The unix_timestamp() function is available in the hive. But it is providing the current timestamp in the second’s format. But the value is not fixed. Hence it is very difficult for optimizing the query and gets the related information. That’s why the unix_timestamp() function will deprecate from the version of hive 2.0.Examples of HiveTimestamp
Following are the example are given below:
As discussed previously, we have the number of predefined functions available in the hive. Let’s explore one by one.1. unix_timestamp()
The UNIX timestamp function is helpful to get the timestamp information in the second format. It is generally useful to calculate the time difference with a different application in Hadoop like YARN, HBase, etc.
Output:2. unix_timestamp(string date)
The UNIX timestamp with string date function helps convert the human-readable time or string date into seconds. It considers the local time zone (the time zone is using by the cluster or node). The string format should be in “YYYY – MM – DD – HH – MM – SS”.
The return data type of unix_timestampfunction is “bigint”.
select unix_timestamp('2024-03-25 16:32:01');
Output:3. unix_timestamp(string date, string pattern)
The UNIX timestamp with string date and patter function is helpful to convert the timestamp in different patterns. As per our requirement, we can get the timestamp in seconds as per “YYYY – MM – DD” or “HH: MM”.
The return data type the unix_timestamp function is “bigint”.
Query – “YYYY – MM – DD” Format
Query – “HH: MM” Format
Output:4. to_date(string timestamp)
In the above function, we can get the complete date information form the timestamp. The timestamp format should in hive timestamp only.
The return data type of to_date function varies from the version of the hive. Suppose the version is below 2.1.0 then its string. If the version is above 2.1.0, then the data type will be “date”.
select to_date('2024-03-25 16:32:01');
Output:5. year(string date)
With the help of the year function, we can fetch the year form string date. The return data type the year function is “int”.
select quarter('2024-03-25 16:32:01');
In the above function, we can fetch the month information form the timestamp. The return data type the monthfunction is “int”.
select month(‘2024-03-25 16:32:01’);
Output:8. hour(string date)
In the above function, we can fetch the hour information form the timestamp.
The return data type the hourfunction is “int”.
select hour('2024-03-25 16:32:01');
Output:9. minute(string date)
In the above function, we can fetch the minute information form the timestamp.
The return data type the minutefunction is “int”.
select minute('2024-03-25 16:32:01');
Output:10. weekofyear(string date)
The return data type the weekofyear function is “int”.
select weekofyear('2024-03-25 16:32:01');
Output:11. datediff(string enddate, string startdate)
With the help of datediff function, we will get the difference between two dates. The output would be in numeric format. The return data type the datediff function is “int”.
select datediff('2024-03-30', '2024-03-25');
In the date_add function, we will get the next date with the respective integer values. We have provided in terms of days. The return data type the date_addfunction is “int”.
select date_add('2024-03-25 16:32:01', 1);
In the date_sub function, we will get the past date value for days integer value.
The return data type the date_sub function is “int”.
select date_sub('2024-03-25 16:32:01', 1);
Output:Advantages of using Hive Timestamp
The hive timestamp is useful to write the automation jobs.
Checks the updated time while inserting the record in the table.
Useful to comparison the timestamp with different services of Hadoop like YARN, HBase and other services.
Very useful in transaction applications, retail industry, etc.
It is helpful in troubleshooting and fixes the hive transactions jobs.Conclusion
We have seen the uncut concept of “Hive Timestamp” with the proper example, explanation, syntax, SQL Query and different functions. With the help of “Hive Timestamp”, we will get the updated information of the hive’s table and current environment. Majorly it will use in automation script, transaction application, retail industry, etc.Recommended Articles
This is a guide to Hive TimeStamp. Here we also discuss the Introduction, and how does timestamp work in a hive? Along with different examples and code implementation. You may also have a look at the following articles to learn more –
Update the detailed information about How Does Opencv Findcontour() Work on the Flu.edu.vn 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!