Edit:
In short:
cap = cv2.VideoCapture(input_loc);
fps = cap.get(cv2.CAP_PROP_FPS)
returns ZeroDivisionError: float division by zero
starting from the 2nd video in the loop. (works fine on 1st video)
Note: already tried solution in Python OpenCV video.get(cv2.CAP_PROP_FPS) returns 0.0 FPS but didn’t solve my issue.
I’m sorry that the title seems very vague since I’m not sure how to describe my issue.
To be short, I guess that OpenCV failed to load the video in started from the second video. Maybe it’s because I forgot to reset something?
My goal is to extract frames from multiple videos, so I’ve implemented a function to do that:
def video_to_frames(input_loc, output_loc, filename, sec):
"""Function to extract frames from input video file
and save them as separate frames in an output directory.
Args:
input_loc: Input video file.
output_loc: Output directory to save the frames.
filename: name of the video file
sec: how many seconds per frame
"""
try:
os.mkdir(output_loc)
except OSError:
pass
# Start capturing the feed
cap = cv2.VideoCapture(input_loc)
# Find the total duration of videos
fps = cap.get(cv2.CAP_PROP_FPS)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
video_length = frame_count/fps
print("Video Length:", video_length)
count = 1
timepoint = count*sec*1000
# Start converting the video
while cap.isOpened():
# Extract the frame
cap.set(cv2.CAP_PROP_POS_MSEC,(timepoint))
ret, frame = cap.read()
for t in range(-2, 3):
cap.set(cv2.CAP_PROP_POS_MSEC,(timepoint + t*50))
ret, frame = cap.read()
cv2.imwrite("{}{}-{}-{}.png".format(output_loc, filename[:-4], count-1, t+2), frame[:480, :640, :]) # the shape of frame should be consistent
count = count + 1 # jump to the next frame
timepoint = count*sec*1000
# If there are no more frames left
if (timepoint > ((video_length -1 ) *1000)):
# Release the feed
cap.release()
# Print stats
print ("{} frames extracted".format(count-1))
break
return video_length, count
To execute this function, I put it in a loop
frames = 0
extracts = 0
total_frames = 0
for file_name in video_list:
input_path = input_path + "{}".format(f)
print (file_name)
video_to_frames(input_path, output_path, file_name, 2)
cv2.destroyAllWindows()
My issue is that extracting the first file seems fine, but once it moves to the next file, there are some problems so I get an error like this:
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-55-002937137b8e> in <module>()
7 input_path = input_path + "{}".format(f)
8 print (file_name)
----> 9 video_to_frames(input_path, output_path, file_name, 2)
10
11 cv2.destroyAllWindows()
<ipython-input-52-e4a4392eaa12> in video_to_frames(input_loc, output_loc, filename, sec)
22 fps = cap.get(cv2.CAP_PROP_FPS)
23 frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
---> 24 video_length = frame_count/fps
25
26 print("Video Length:", video_length)
ZeroDivisionError: float division by zero
Anyone knows why and how should I deal with this?
Here are five options for dealing with error Msg 8134 “Divide by zero error encountered” in SQL Server.
First, here’s an example of code that produces the error we’re talking about:
SELECT 1 / 0;
Result:
Msg 8134, Level 16, State 1, Line 1 Divide by zero error encountered.
We get the error because we’re trying to divide a number by zero. Mathematically, this does not make any sense. You can’t divide a number by zero and expect a meaningful result.
To deal with this error, we need to decide what should be returned when we try to divide by zero. For example, we might want a null value to be returned. Or we might want zero to be returned. Or some other value.
Below are some options for dealing with this error.
Option 1: The NULLIF()
Expression
A quick and easy way to deal with this error is to use the NULLIF()
expression:
SELECT 1 / NULLIF( 0, 0 );
Result:
NULL
NULLIF()
returns NULL
if the two specified expressions are the same value. It returns the first expression if the two expressions are different. Therefore, if we use zero as the second expression, we will get a null value whenever the first expression is zero. Dividing a number by NULL
results in NULL
.
Actually, SQL Server already returns NULL
on a divide-by-zero error, but in most cases we don’t see this, due to our ARITHABORT
and ANSI_WARNINGS
settings (more on this later).
Option 2: Add the ISNULL()
Function
In some cases, you might prefer to return a value other than NULL
.
In such cases, you can pass the previous example to the ISNULL()
function:
SELECT ISNULL(1 / NULLIF( 0, 0 ), 0);
Result:
0
Here I specified that zero should be returned whenever the result is NULL
.
Be careful though. In some cases, returning zero might be inappropriate. For example, if you’re dealing with inventory supplies, specifying zero might imply that there are zero products, which might not be the case.
Option 3: Use a CASE
Statement
Another way to do it is to use a CASE
statement:
DECLARE @n1 INT = 20;
DECLARE @n2 INT = 0;
SELECT CASE
WHEN @n2 = 0
THEN NULL
ELSE @n1 / @n2
END
Result:
NULL
Option 4: The SET ARITHABORT
Statement
The SET ARITHABORT
statement ends a query when an overflow or divide-by-zero error occurs during query execution. We can use it in conjunction with SET ANSI WARNINGS
to return NULL
whenever the divide-by-zero error might occur:
SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;
SELECT 20 / 0;
Result:
NULL
Microsoft recommends that you always set ARITHABORT
to ON
in your logon sessions, and that setting it to OFF
can negatively impact query optimisation, leading to performance issues.
Some clients (such as SQL Server Management Studio) set ARITHABORT
to ON
by default. This is why you probably don’t see the NULL
value being returned when you divide by zero. You can use SET ARITHIGNORE
to change this behaviour if you prefer.
Option 5: The SET ARITHIGNORE
Statement
The SET ARITHIGNORE
statement controls whether error messages are returned from overflow or divide-by-zero errors during a query:
SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;
SET ARITHIGNORE ON;
SELECT 1 / 0 AS Result_1;
SET ARITHIGNORE OFF;
SELECT 1 / 0 AS Result_2;
Result:
Commands completed successfully. Commands completed successfully. Commands completed successfully. +------------+ | Result_1 | |------------| | NULL | +------------+ (1 row affected) Commands completed successfully. +------------+ | Result_2 | |------------| | NULL | +------------+ Division by zero occurred.
Here, I set ARITHABORT
and ANSI_WARNINGS
to OFF
so that the statement wasn’t aborted due to the error, and NULL
is returned whenever there’s a divide-by-zero error.
Note that the SET ARITHIGNORE
setting only controls whether an error message is returned. SQL Server returns a NULL
in a calculation involving an overflow or divide-by-zero error, regardless of this setting.
In the above example we can see that when ARITHIGNORE
is ON
, the division by zero error is not returned. When it’s OFF
, the division by zero error message is returned.
Ошибка Fatal error: Uncaught DivisionByZeroError: Division by zero in — Как избежать деления на ноль в программировании
Одной из наиболее распространенных и сложных проблем, с которыми сталкиваются программисты, является ошибка DivisionByZeroError: Division by zero. Это ошибка возникает, когда вы пытаетесь выполнить деление на ноль в своем коде. В этой статье мы рассмотрим, почему она возникает, как ее избежать и предоставим несколько полезных советов, которые помогут вам избежать этой ошибки в своих программах.
Во многих языках программирования деление на ноль считается недопустимой операцией. При попытке выполнить такое деление возникает ошибка DivisionByZeroError. Продолжение выполнения программы невозможно, и она останавливается, выдавая сообщение об ошибке. Это может привести к сбою программы, потере данных или некорректным результатам.
Возможные причины возникновения ошибки DivisionByZeroError:
1. Неправильный ввод данных. Если вводные данные в программе предполагают деление на какое-либо число, и пользователь вводит ноль, ошибка DivisionByZeroError может быть вызвана неправильными или неожиданными вводными данными.
2. Неправильное использование переменных. Если определенная переменная, используемая в операции деления, равна нулю, то ошибка может возникнуть при выполнении операции деления.
3. Неправильно написанный код. Некоторые программисты могут некорректно описывать условия или предположения, при которых выполняется деление. Например, они могут забыть проверить, что делитель ненулевой, что может привести к ошибке. Также возможны опечатки, как в коде, так и во вводных данных, которые будут приводить к ошибках деления на ноль.
Как избежать ошибок DivisionByZeroError:
1. Проверьте вводные данные. Перед выполнением операции деления убедитесь, что вводные данные являются допустимыми. Если вы пишете программу, которая ожидает ввод чисел для дальнейших вычислений, убедитесь, что вы проверяете, что ввод не является нулем или иным недопустимым значением.
2. Используйте условные выражения. Перед выполнением операции деления используйте условные выражения для проверки допустимых условий, например, проверьте, что делитель не равен нулю. Если условие не выполняется, вы можете сообщить пользователю об ошибке и попросить ввести другое значение.
3. Используйте исключения (exceptions). Во многих языках программирования есть механизм исключений, позволяющий обрабатывать ошибки в коде. Вы можете использовать оператор try-catch, чтобы перехватить и обработать ошибку DivisionByZeroError, предоставив пользователю информацию о проблеме и, если это возможно, восстановить работу программы.
4. Проверьте делитель перед операцией деления. Если вы предполагаете, что делитель может быть равен нулю или некорректному значению, проверьте его перед делением. Если делитель является недопустимым, вы можете присвоить ему другое значение или выполнить другие действия в зависимости от требуемого поведения вашей программы.
5. Используйте функции-помощники (helper functions) для выполнения проверок. Если вы выполняете множество операций деления в своей программе, может иметь смысл создать вспомогательную функцию, которая будет выполнять проверку делителя. Такой подход упростит ваш код и позволит избежать повторения кода.
6. Обрабатывайте ошибки DivisionByZeroError. Если ошибка DivisionByZeroError все равно возникает, необходимо обработать ее. Одним из возможных решений может быть вывод сообщения об ошибке и завершение программы, чтобы пользователь мог принять меры по ее исправлению или связаться с вами для получения дополнительной помощи.
В заключение, ошибка DivisionByZeroError является распространенной и сложной для обработки проблемой в программировании. Однако вы можете избежать ее, следуя некоторым основным принципам и правилам. Проверяйте вводные данные, используйте условные выражения и исключения, проверяйте делитель перед операцией деления и обрабатывайте ошибки, если они все равно возникают. Это поможет вам создавать более надежные и стабильные программы.
Ошибка — Warning: Division by zero in, как исправить
Ошибка Division by zero, как исправить ошибку Warning: Division by zero in
division by zero это не ошибка при установке игры — это обычное деление на ноль…
- Что означает ошибка Division by zero
- Как исправить ошибку Warning: Division by zero in
Что означает ошибка Division by zero
У нас встретилась вот такая ошибка :
Warning: Division by zero in адрес on line 18
Прежде чем приступать к нашей ошибке — давайте просто попробуем перевести!
Warning: Division by zero — перевод
Переведем данную ошибку с английского и нам сразу станет все ясно!
Warning — предупреждение, сигнал сущ
Division — деление, отдел, раздел, распределение сущ
by — по, посредством предл
zero — ноль сущ
Итого, если мы соберем данную фразу «Warning: Division by zero» на русском, то получим :
Внимание! Ошибка деления на ноль!
как исправить ошибку Warning: Division by zero in
Дл ятого, чтобы исправить ошибку «Warning: Division by zero in» нам понадобится скриншот ошибки, который мы приводили раньше. смотрим на него и видим последнее слово и число, line — это линия в файле, 18 — это номер линии где ошибка.
line 18
И та часть, которая размыта — это адрес, по которому находится файл с ошибкой Warning: Division by zero in
Далее находим данный файл и удаляем ошибку!
Не благодарите, но ссылкой можете поделиться!
COMMENTS+
BBcode
15.08.2023 16:53
михаил
а если это сделано для диаграммы values / maxv) *100
ответить
15.08.2023 17:50
Марат
михаил
Значит в «maxv» сидит 0.
ответить
This article explores the SQL divide by zero error and various methods for eliminating this.
Introduction
We all know that in math, it is not possible to divide a number by zero. It leads to infinity:
Source: www.1dividedby0.com
If you try to do in calculator also, you get the error message – Cannot Divide by zero:
We perform data calculations in SQL Server for various considerations. Suppose we perform an arithmetic division operator for calculating a ratio of products in a store. Usually, the division works fine, and we get the ratio:
DECLARE @Product1 INT; DECLARE @Product2 INT; SET @Product1 = 50; SET @Product2 = 10; SELECT @Product1 / @Product2 ProductRatio; |
Someday, the product2 quantity goes out of stock and that means we do not have any quantity for product2. Let’s see how the SQL Server query behaves in this case:
DECLARE @Product1 INT; DECLARE @Product2 INT; SET @Product1 = 50; SET @Product2 = 0; SELECT @Product1 / @Product2 ProductRatio; |
We get SQL divide by zero error messages (message id 8134, level 16):
We do not want our code to fail due to these errors. It is a best practice to write code in such a way that it does not give divide by zero message. It should have a mechanism to deal proactively with such conditions.
SQL Server provides multiple methods for avoiding this error message. Let’s explore it in the next section.
Method 1: SQL NULLIF Function
We use NULLIF function to avoid divide by zero error message.
The syntax of NULLIF function:
NULLIF(expression1, expression2) |
It accepts two arguments.
-
If both the arguments are equal, it returns a null value
For example, let’s say both arguments value is 10:
SELECT NULLIF(10, 10) result;
In the screenshot, we can see that the output is null:
-
If both the arguments are not equal, it returns the value of the first argument
In this example, both argument values differ. It returns the output as value of first argument 10:
SELECT NULLIF(10, 5) result;
Let’s modify our initial query using the SQL NULLIF statement. We place the following logic using NULLIF function for eliminating SQL divide by zero error:
- Use NULLIF function in the denominator with second argument value zero
- If the value of the first argument is also, zero, this function returns a null value. In SQL Server, if we divide a number with null, the output is null as well
- If the value of the first argument is not zero, it returns the first argument value and division takes place as standard values
DECLARE @Product1 INT; DECLARE @Product2 INT; SET @Product1 = 50; SET @Product2 = 0; SELECT @Product1 / NULLIF(@Product2,0) ProductRatio; |
Execute this modified query. We can see the output NULL because denominator contains value zero.
Do we want null value in the output? Is there any method to avoid null and display a definite value?
Yes, we can use SQL ISNULL function to avoid null values in the output. This function replaces the null value in the expression1 and returns expression2 value as output.
Let’s explore the following query with a combination of SQL NULLIF and SQL ISNULL function:
- First argument ((@Product1 / NULLIF(@Product2,0)) returns null
- We use the ISNULL function and specify the second argument value zero. As we have the first argument null, the output of overall query is zero (second argument value)
DECLARE @Product1 INT; DECLARE @Product2 INT; SET @Product1 = 50; SET @Product2 = 0; SELECT ISNULL(@Product1 / NULLIF(@Product2,0),0) ProductRatio; |
Method 2: Using CASE statement to avoid divide by zero error
We can use a CASE statement in SQL to return values based on specific conditions. Look at the following query. It does the following task with the Case statement.
The Case statement checks for the value of @Product2 parameter:
- If the @Product2 value is zero, it returns null
- If the above condition is not satisfied, it does the arithmetic operation (@Product1/@Product2) and returns the output
Method 3: SET ARITHABORT OFF
We can use set methods to control query behavior. By default, SQL Server has a default value of SET ARITHABORT is ON. We get SQL divide by zero error in the output using the default behavior.
The T-SQL syntax for controlling the ARITHABORT option is shown below:
SET ARITHABORT { ON | OFF } |
-
Using ARITHABORT ON, the query will terminate with divide by zero message. It is the default behavior. For this demo, let’s enable it using the SET ARITHABORT ON statement:
SET ARITHABORT ON — Default
SET ANSI_WARNINGS ON
DECLARE @Product1 INT;
DECLARE @Product2 INT;
SET @Product1 = 50;
SET @Product2 = 0;
SELECT @Product1 / @Product2 ProductRatio;
We get the SQL divide by zero error messages:
-
Using ARITHABORT OFF, the batch will terminate and returns a null value. We need to use ARITHABORT in combination with SET ANSI_WARNINGS OFF to avoid the error message:
We can use the following query to check the current setting for the ARITHABORT parameter:
DECLARE @ARITHABORT VARCHAR(3) = ‘OFF’;
IF ( (64 & @@OPTIONS) = 64 ) SET @ARITHABORT = ‘ON’;
SELECT @ARITHABORT AS ARITHABORT;
The default ARITHABORT setting for SSMS is ON. We can view it using SSMS Tools properties. Navigate to Tools -> Options -> Advanced:
Many client applications or drivers provide a default value of ARITHABORT is OFF. The different values might force SQL Server to produces a different execution plan, and it might create performance issues. You should also match the setting similar to a client application while troubleshooting the performance issues.
Note: You should not modify the value of ARITHABORT unless required. It might create performance issues, as well. I would suggest using alternative methods (as described earlier) for avoiding SQL divide by zero error.
Conclusion
In this article, we explored the various methods for avoiding SQL divide by zero error. It is best practice to be proactive and use these mechanisms so that code does not fail in real-time.
- Author
- Recent Posts
Hi! I am Rajendra Gupta, Database Specialist and Architect, helping organizations implement Microsoft SQL Server, Azure, Couchbase, AWS solutions fast and efficiently, fix related issues, and Performance Tuning with over 14 years of experience.
I am the author of the book «DP-300 Administering Relational Database on Microsoft Azure». I published more than 650 technical articles on MSSQLTips, SQLShack, Quest, CodingSight, and SeveralNines.
I am the creator of one of the biggest free online collections of articles on a single topic, with his 50-part series on SQL Server Always On Availability Groups.
Based on my contribution to the SQL Server community, I have been recognized as the prestigious Best Author of the Year continuously in 2019, 2020, and 2021 (2nd Rank) at SQLShack and the MSSQLTIPS champions award in 2020.
Personal Blog: https://www.dbblogger.com
I am always interested in new challenges so if you need consulting help, reach me at rajendra.gupta16@gmail.com
View all posts by Rajendra Gupta