Your loop filters a pandas DataFrame for each camera ID and passes the filtered column straight into cv2.VideoCapture. Python stops with TypeError: cannot convert the series to <class 'int'>. The capture call is not the problem, and neither is the DataFrame: df.loc[mask, 'path'] returns a pandas Series, while cv2.VideoCapture accepts exactly one str path or one int device index. This guide shows where the Series comes from, how to extract a single value with .iat[0], and how to guard the two cases that break the naive fix: a filter that matches nothing and one that matches several rows. Everything below is about recorded files; live cameras open by index or pipeline instead.
What the error message is telling you
cv2.VideoCapture has two documented overloads in the VideoCapture class reference: a filename str, and an int device index. The Python binding inspects the argument type at call time. A pandas Series is neither a str nor an int, so the binding falls back to the integer overload, and converting a multi-element Series to int is what raises the message you are seeing.
Three lines reproduce it outside any inspection pipeline:
import cv2
import pandas as pd
log = pd.DataFrame({"cameraCD": ["0008"], "path": ["clip_0008.mp4"]})
cap = cv2.VideoCapture(log.loc[log["cameraCD"] == "0008", "path"])
# TypeError: cannot convert the series to <class 'int'>
The DataFrame is valid, the filter is valid, and the file may even exist. The selection has the wrong type, and one print settles it:
sel = log.loc[log["cameraCD"] == "0008", "path"]
print(type(sel)) # <class 'pandas.core.series.Series'>
Why a filter returns a Series instead of a string
A boolean mask can match any number of rows, so pandas returns every matched value as a Series — even when exactly one row matches. This is documented pandas indexing behaviour: a mask selection gives a Series, a scalar label such as log.loc[0, 'path'] gives the value itself. One row in, one str out; a mask in, a Series out, whatever the match count — 0, 1 or 100.
The camera list at the top of the loop needs no change. Series.unique() returns a NumPy array, and iterating over it yields one str per camera code. Only the column selection handed to cv2.VideoCapture lacks the final step.
Resist .squeeze() as the shortcut. On a one-element Series it returns the scalar; on a multi-row result it quietly returns the Series again (or a DataFrame if you selected several columns), so the same error reappears one line later. .iat[0] is the cleaner choice, for reasons the worked example below shows.
The fix: pass one scalar path with .iat[0]
Work through four steps:
- Filter into a named Series so the match count is checkable.
- Check
len(rows)before extracting anything. - Extract the scalar with
.iat[0];.iloc[0]is equivalent here. - Open the capture and test
cap.isOpened()immediately.
camera: str = "0008" # loop key, from log["cameraCD"].unique()
rows = log.loc[log["cameraCD"] == camera, "path"] # pandas Series
if len(rows) == 0:
raise ValueError(f"no log row for camera {camera}")
path: str = rows.iat[0] # one str
cap = cv2.VideoCapture(path)
if not cap.isOpened():
raise IOError(f"cannot open {path}")
Applied to both path columns of the two-file case:
cap1 = cv2.VideoCapture(log.loc[log["cameraCD"] == camera, "path"].iat[0])
cap2 = cv2.VideoCapture(log.loc[log["cameraCD"] == camera, "path2"].iat[0])
Worked example: one clip per camera from a recording log
Inputs follow the schema of the failure case: a recording log with one row per camera per day, and one path column per stream. The DataFrame log has columns cameraCD (str), date (str), path (str) and path2 (str); the values are illustrative, the types are not.
log = pd.DataFrame({
"cameraCD": ["0008", "0008"],
"date": ["2019-07-30", "2019-07-31"],
"path": ["line_a_0730.mp4", "line_a_0731.mp4"],
"path2": ["line_b_0729.mp4", "line_b_0730.mp4"],
})
camera: str = "0008" # loop key from log["cameraCD"].unique()
The rule in words: mask, then Series, then length check, then scalar, then open. The arithmetic, step by step:
-
log["cameraCD"] == "0008"evaluates to the mask[True, True]— camera 0008 owns both rows. -
log.loc[mask, "path"]returns a two-element Series, solen(rows)is 2. - Two matches mean the camera code alone does not identify one clip; the day decides it.
rows = log.loc[(log["cameraCD"] == camera) & (log["date"] == "2019-07-30"), "path"]
assert len(rows) == 1
path: str = rows.iat[0] # 'line_a_0730.mp4'
The test that proves the result:
import cv2
print(type(path)) # <class 'str'>
cap = cv2.VideoCapture(path)
print(cap.isOpened()) # True: file found and demuxer opened
ok, frame = cap.read()
print(ok, frame.shape if ok else None) # True (480, 640, 3)
The frame shape is illustrative — your clip's resolution sets it; 480 rows by 640 columns is just a common SD example. What matters is ok being True; a False there is a file or codec problem, not a type problem, and OpenCV cap.read() returning false covers that family.
Decision, with the threshold on len(rows): exactly 1 opens the clip. 0 skips the camera and logs the ID, because .iat[0] on an empty Series raises IndexError. 2 or more means the key is not unique, so narrow the mask with a second column or loop over the matched rows and open each path in turn.
Other causes when the message comes back
Ranked by how often each turns up:
- A second cv2.VideoCapture call still passes a slice. Search the script for
VideoCapture(and check every argument — the second path column is the one most often forgotten. - The Series was stored earlier in the script. A variable assigned as
df.loc[...]keeps its Series type for the rest of the run; check every later use of it. - Double brackets created a DataFrame:
log[["path"]]is a one-column DataFrame selection, which will not open either. Single brackets return the Series you want. - A list or NumPy array of paths went in instead of one path — also a TypeError at the same line.
Test each by printing type(x) on the line before the call. The fix is always the same: reduce the argument to one str. Once the type is right, remaining failures move to the path content — separators and escapes in Python image file path errors across operating systems, paths that break only on the deployment machine in Machine vision model file paths: fix deployment errors. Wrong-type arguments at construction have a family of small traps; OpenCV VideoCapture capitalization and camera initialization covers the neighbouring ones.
Prevention: a helper that opens exactly one clip
Put the guard in one place and every caller inherits it:
import cv2
import pandas as pd
def open_clip(df: pd.DataFrame, key: str, column: str = "path"):
# Open one clip for one camera key, or return None.
rows = df.loc[df["cameraCD"] == key, column]
if len(rows) != 1:
return None # zero or several matches: caller decides
path: str = rows.iat[0]
cap = cv2.VideoCapture(path)
return cap if cap.isOpened() else None
Keep the ID and path columns as text. Read the log with dtype=str so codes survive as written:
Two more habits: a unit test with a one-row DataFrame asserting the helper returns an opened capture for a known file; and cap.release() on every capture before the next iteration, so file handles do not pile up across a long review run.
Checks before you rerun the script
- The argument to cv2.VideoCapture prints as
<class 'str'>, notpandas.core.series.Series. - The filtered Series length was checked before
.iat[0]: zero matches skip with a log line, several matches narrow the mask. -
cap.isOpened()is True right after construction. - The first
cap.read()returnsokas True. - The log was loaded with
dtype=str, so camera codes keep their leading zeros. - Every capture is released after use.
Those six checks clear this error and the two that usually follow it: silent empty matches, and unopenable paths.
If the review task grows into live inspection instead of replaying files, the hardware decision starts at the area scan cameras category — GigE, USB3 and CoaXPress models for PC-based capture — or at smart cameras, which run the inspection on the device with no PC in the loop; the camera finder filters both by resolution, interface and shutter. For an open error that survives all of the above, bring the traceback to the contact page.
Questions
Does the same fix apply to cv2.imread for image files?
Yes. cv2.imread also takes exactly one filename string, and a pandas Series raises the same TypeError at that call. Extract the value with .iat[0] first. The same applies to any function in the script that expects a path: a mask selection outside a loop is nearly always the culprit, and print(type(x)) confirms it in one line.
What is the difference between .iat[0], .iloc[0] and .values[0]?
.iat[0] and .iloc[0] both return the scalar at position 0 of the filtered Series, and .iat is the strict scalar accessor, the fastest choice for this job. .values[0] reads the first element of the underlying NumPy array and works here too. Prefer .iat when a key might be missing: it raises IndexError on an empty selection, so a lost camera shows up as a visible failure rather than a silent skip.
How do I open the clips for every camera in one run?
Loop over the unique keys and call the same guarded helper for each: for key in sorted(log["cameraCD"].unique()): cap = open_clip(log, key). A None return names the key to investigate instead of crashing the batch. Release each capture with cap.release() before the next iteration so file handles do not accumulate over a long run.
Why does my camera code 0008 stop matching after the log is loaded?
pandas reads a column of digits as integers, so 0008 becomes the number 8 and the mask log["cameraCD"] == "0008" matches zero rows; .iat[0] then raises IndexError instead of the type error. Reload with dtype=str, or repair in place with log["cameraCD"] = log["cameraCD"].astype(str).str.zfill(4) when every code is four characters wide.
The type error is gone but isOpened() returns False — what now?
The argument is a proper string now, so the failure moved to the file itself. If the clips sit on a cloud drive in a notebook, mount the drive first; its paths do not resolve until then. On disk, print the path and confirm the file exists at that exact spelling from the working directory, then confirm an installed codec can demux the container. isOpened() False right after construction is the signal; test it before the first read().