我正在尝试运行导入 opencv 的 python 脚本,我已经成功安装了 opencv,我可以看到安装和版本,但是当我尝试通过脚本调用它时,我收到导入错误
(cv) nikhil@nikhil-VirtualBox:~/object_detection_projects/opencv_traffic_counting$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>>
[1]+ Stopped python3
(cv) nikhil@nikhil-VirtualBox:~/object_detection_projects/opencv_traffic_counting$ sudo python3 traffic.py
Traceback (most recent call last):
File "traffic.py", line 8, in <module>
import cv2
ImportError: No module named 'cv2'
我该如何解决这个问题?我使用的是 Ubuntu 16.04,我尝试运行的脚本是
import os
import logging
import logging.handlers
import random
import numpy as np
import skvideo.io
import cv2
import matplotlib.pyplot as plt
import utils
# without this some strange errors happen
cv2.ocl.setUseOpenCL(False)
random.seed(123)
from pipeline import (
PipelineRunner,
ContourDetection,
Visualizer,
CsvWriter,
VehicleCounter)
# ============================================================================
IMAGE_DIR = "/Desktop"
VIDEO_SOURCE = "Car Detection in Traffic with Deep Learning Toolkit for LabVIEW.mp4"
SHAPE = (720, 1280) # HxW
EXIT_PTS = np.array([
[[732, 720], [732, 590], [1280, 500], [1280, 720]],
[[0, 400], [645, 400], [645, 0], [0, 0]]
])
# ============================================================================
def train_bg_subtractor(inst, cap, num=500):
'''
BG substractor need process some amount of frames to start giving result
'''
print ('Training BG Subtractor...')
i = 0
for frame in cap:
inst.apply(frame, None, 0.001)
i += 1
if i >= num:
return cap
def main():
log = logging.getLogger("main")
# creating exit mask from points, where we will be counting our vehicles
base = np.zeros(SHAPE + (3,), dtype='uint8')
exit_mask = cv2.fillPoly(base, EXIT_PTS, (255, 255, 255))[:, :, 0]
# there is also bgslibrary, that seems to give better BG substruction, but
# not tested it yet
bg_subtractor = cv2.createBackgroundSubtractorMOG2(
history=500, detectShadows=True)
# processing pipline for programming conviniance
pipeline = PipelineRunner(pipeline=[
ContourDetection(bg_subtractor=bg_subtractor,
save_image=True, image_dir=IMAGE_DIR),
# we use y_weight == 2.0 because traffic are moving vertically on video
# use x_weight == 2.0 for horizontal.
VehicleCounter(exit_masks=[exit_mask], y_weight=2.0),
Visualizer(image_dir=IMAGE_DIR),
CsvWriter(path='./', name='report.csv')
], log_level=logging.DEBUG)
# Set up image source
# You can use also CV2, for some reason it not working for me
cap = skvideo.io.vreader(VIDEO_SOURCE)
# skipping 500 frames to train bg subtractor
train_bg_subtractor(bg_subtractor, cap, num=500)
_frame_number = -1
frame_number = -1
for frame in cap:
if not frame.any():
log.error("Frame capture failed, stopping...")
break
# real frame number
_frame_number += 1
# skip every 2nd frame to speed up processing
if _frame_number % 2 != 0:
continue
# frame number that will be passed to pipline
# this needed to make video from cutted frames
frame_number += 1
# plt.imshow(frame)
# plt.show()
# return
pipeline.set_context({
'frame': frame,
'frame_number': frame_number,
})
pipeline.run()
# ============================================================================
if __name__ == "__main__":
log = utils.init_logging()
if not os.path.exists(IMAGE_DIR):
log.debug("Creating image directory `%s`...", IMAGE_DIR)
os.makedirs(IMAGE_DIR)
main()
答案1
首先,您必须检查您的 lepi 上是否已安装 opencv。您可以使用以下命令来执行此操作。
python3 -c "import cv2; print(cv2.__version__)"
它会显示你的 opencv 版本。但如果没有,可能你的 opencv-python 尚未安装。然后尝试使用此命令进行安装。
sudo apt install python3-opencv