Opencv 3 1 0
Author: t | 2025-04-24
Problem with Opencv and Python. 0. Python For OpenCV. OpenCV 2.4.3 and Python. 0. OpenCV Python . OpenCV for Python 3.5.1. 3. OpenCV 3 Python. 2. Opencv Pythonprogram. 0. Opencv Raspberry python3. Hot Network Questions How to understand parking rules in Austria (street parking)
0 0 0 3 5 4 0 0 1 3 3 4 4 0 0 0 0 3 3 3 1 0 3 6 1 0 0 - fill-a
Nonzerox[left_lane_inds]lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds]righty = nonzeroy[right_lane_inds]return leftx, lefty, rightx, righty, out_imgdef fit_polynomial_first_lane(binary_warped):leftx, lefty, rightx, righty, out_img = find_lane_pixels(binary_warped)left_fit = np.polyfit(lefty, leftx, 2)right_fit = np.polyfit(righty, rightx, 2)ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0])try:left_fitx = left_fit[0] * ploty2 + left_fit[1] * ploty + left_fit[2]right_fitx = right_fit[0] * ploty2 + right_fit[1] * ploty + right_fit[2]except TypeError:print('The function failed to fit a line!')left_fitx = 1 * ploty2 + 1 * plotyright_fitx = 1 * ploty2 + 1 * plotyout_img[lefty, leftx] = [255, 0, 0]out_img[righty, rightx] = [0, 0, 255]left_pts = np.transpose(np.vstack((left_fitx, ploty))).astype(np.int32)right_pts = np.transpose(np.vstack((right_fitx, ploty))).astype(np.int32)cv2.polylines(out_img, np.int32([left_pts]), False, (255, 255, 0), thickness=5)cv2.polylines(out_img, np.int32([right_pts]), False, (255, 255, 0), thickness=5)return left_fit, right_fit, out_imgbinary_warped pixel range: 0 to 255binary_warped shape: (720, 1280, 3), type: uint8out_img shape: (720, 1280, 9), type: uint8error Traceback (most recent call last) in ()146147 # Find lane pixels and fit polynomial--> 148 left_fit, right_fit, out_img = fit_polynomial_first_lane(binary_warped)149150 # Plot the results1 frames in find_lane_pixels(binary_warped)66 win_xright_high = min(binary_warped.shape[1], win_xright_high)67---> 68 cv2.rectangle(out_img, (win_xleft_low, win_y_low), (win_xleft_high, win_y_high), (0, 255, 0), 2)69 cv2.rectangle(out_img, (win_xright_low, win_y_low), (win_xright_high, win_y_high), (0, 255, 0), 2)70error: OpenCV(4.8.0) /io/opencv/modules/core/src/copy.cpp:71: error: (-215:Assertion failed) cn Problem with Opencv and Python. 0. Python For OpenCV. OpenCV 2.4.3 and Python. 0. OpenCV Python . OpenCV for Python 3.5.1. 3. OpenCV 3 Python. 2. Opencv Pythonprogram. 0. Opencv Raspberry python3. Hot Network Questions How to understand parking rules in Austria (street parking) Import streamlit as st import cv2 import tflite_runtime.interpreter as tflite import numpy as np import threading from zipfile import ZipFile BOX_COLOR = (0, 255, 255) #Yellow TF_LITE_MODEL = './lite-model_ssd_mobilenet_v1_1_metadata_2.tflite' CLASSES_OF_INTEREST = ['person', 'car', 'cat', 'dog'] VIDEO_SOURCE = 0 # an integer number for an OpenCV supported camera or any video file def draw_boxes(frame, boxes, threshold, labelmap, obj_of_int): (h, w) = frame.shape[:2] #np array shapes are h,w OpenCV uses w,h for (t, l, b, r), label_id, c in boxes: if c > threshold and label_id in obj_of_int: top_left, bottom_right = (int(l*w), int(t*h)), (int(r*w), int(b*h)) cv2.rectangle(frame, top_left, bottom_right, BOX_COLOR, 2) cv2.putText(frame, f'{labelmap[int(label_id)]} {c:.4f}', top_left, cv2.FONT_HERSHEY_PLAIN, 1, BOX_COLOR) return frame def resize_keep_aspect(img, req_shape): ratio = max((img.shape[1]/req_shape[0], img.shape[0]/req_shape[1])) new_h, new_w = int(img.shape[0]/ratio), int(img.shape[1]/ratio) img = cv2.resize(img, (new_w, new_h)) img = cv2.copyMakeBorder(img, 0, (req_shape[1]-new_h), 0, (req_shape[0]-new_w), cv2.BORDER_CONSTANT) return img, (req_shape[1]/new_h, req_shape[0]/new_w) class CameraThread(threading.Thread): def __init__(self, name='CameraThread'): super().__init__(name=name, daemon=True) self.stop_event = False self.open_camera() self.setup_inference_engine() self._frame, self.results = np.zeros((300,300,3), dtype=np.uint8), [] #initial empty frame self.lock = threading.Lock() self.log_counter = 0 def open_camera(self): self.webcam = cv2.VideoCapture(VIDEO_SOURCE) def setup_inference_engine(self): self.intp = tflite.Interpreter(model_path=TF_LITE_MODEL) self.intp.allocate_tensors() self.input_idx = self.intp.get_input_details()[0]['index'] self.output_idxs = [i['index'] for i in self.intp.get_output_details()[:3]] def process_frame(self, img): _img, (rh, rw) = resize_keep_aspect(img, (300,300)) # cv2.resize(img, (300, 300)) self.intp.set_tensor(self.input_idx, _img[np.newaxis, :]) self.intp.invoke() boxes, label_id, conf = [self.intp.get_tensor(idx).squeeze() for idx in self.output_idxs] boxes = [(t*rh, l*rw, b*rh, r*rw) for (t, l, b, r) in boxes] # scale the coords back return list(zip(boxes, label_id, conf)) def run(self): while not self.stop_event: ret, img = self.webcam.read() if not ret: #re-open camera if read fails. UsefulComments
Nonzerox[left_lane_inds]lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds]righty = nonzeroy[right_lane_inds]return leftx, lefty, rightx, righty, out_imgdef fit_polynomial_first_lane(binary_warped):leftx, lefty, rightx, righty, out_img = find_lane_pixels(binary_warped)left_fit = np.polyfit(lefty, leftx, 2)right_fit = np.polyfit(righty, rightx, 2)ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0])try:left_fitx = left_fit[0] * ploty2 + left_fit[1] * ploty + left_fit[2]right_fitx = right_fit[0] * ploty2 + right_fit[1] * ploty + right_fit[2]except TypeError:print('The function failed to fit a line!')left_fitx = 1 * ploty2 + 1 * plotyright_fitx = 1 * ploty2 + 1 * plotyout_img[lefty, leftx] = [255, 0, 0]out_img[righty, rightx] = [0, 0, 255]left_pts = np.transpose(np.vstack((left_fitx, ploty))).astype(np.int32)right_pts = np.transpose(np.vstack((right_fitx, ploty))).astype(np.int32)cv2.polylines(out_img, np.int32([left_pts]), False, (255, 255, 0), thickness=5)cv2.polylines(out_img, np.int32([right_pts]), False, (255, 255, 0), thickness=5)return left_fit, right_fit, out_imgbinary_warped pixel range: 0 to 255binary_warped shape: (720, 1280, 3), type: uint8out_img shape: (720, 1280, 9), type: uint8error Traceback (most recent call last) in ()146147 # Find lane pixels and fit polynomial--> 148 left_fit, right_fit, out_img = fit_polynomial_first_lane(binary_warped)149150 # Plot the results1 frames in find_lane_pixels(binary_warped)66 win_xright_high = min(binary_warped.shape[1], win_xright_high)67---> 68 cv2.rectangle(out_img, (win_xleft_low, win_y_low), (win_xleft_high, win_y_high), (0, 255, 0), 2)69 cv2.rectangle(out_img, (win_xright_low, win_y_low), (win_xright_high, win_y_high), (0, 255, 0), 2)70error: OpenCV(4.8.0) /io/opencv/modules/core/src/copy.cpp:71: error: (-215:Assertion failed) cn
2025-04-18Import streamlit as st import cv2 import tflite_runtime.interpreter as tflite import numpy as np import threading from zipfile import ZipFile BOX_COLOR = (0, 255, 255) #Yellow TF_LITE_MODEL = './lite-model_ssd_mobilenet_v1_1_metadata_2.tflite' CLASSES_OF_INTEREST = ['person', 'car', 'cat', 'dog'] VIDEO_SOURCE = 0 # an integer number for an OpenCV supported camera or any video file def draw_boxes(frame, boxes, threshold, labelmap, obj_of_int): (h, w) = frame.shape[:2] #np array shapes are h,w OpenCV uses w,h for (t, l, b, r), label_id, c in boxes: if c > threshold and label_id in obj_of_int: top_left, bottom_right = (int(l*w), int(t*h)), (int(r*w), int(b*h)) cv2.rectangle(frame, top_left, bottom_right, BOX_COLOR, 2) cv2.putText(frame, f'{labelmap[int(label_id)]} {c:.4f}', top_left, cv2.FONT_HERSHEY_PLAIN, 1, BOX_COLOR) return frame def resize_keep_aspect(img, req_shape): ratio = max((img.shape[1]/req_shape[0], img.shape[0]/req_shape[1])) new_h, new_w = int(img.shape[0]/ratio), int(img.shape[1]/ratio) img = cv2.resize(img, (new_w, new_h)) img = cv2.copyMakeBorder(img, 0, (req_shape[1]-new_h), 0, (req_shape[0]-new_w), cv2.BORDER_CONSTANT) return img, (req_shape[1]/new_h, req_shape[0]/new_w) class CameraThread(threading.Thread): def __init__(self, name='CameraThread'): super().__init__(name=name, daemon=True) self.stop_event = False self.open_camera() self.setup_inference_engine() self._frame, self.results = np.zeros((300,300,3), dtype=np.uint8), [] #initial empty frame self.lock = threading.Lock() self.log_counter = 0 def open_camera(self): self.webcam = cv2.VideoCapture(VIDEO_SOURCE) def setup_inference_engine(self): self.intp = tflite.Interpreter(model_path=TF_LITE_MODEL) self.intp.allocate_tensors() self.input_idx = self.intp.get_input_details()[0]['index'] self.output_idxs = [i['index'] for i in self.intp.get_output_details()[:3]] def process_frame(self, img): _img, (rh, rw) = resize_keep_aspect(img, (300,300)) # cv2.resize(img, (300, 300)) self.intp.set_tensor(self.input_idx, _img[np.newaxis, :]) self.intp.invoke() boxes, label_id, conf = [self.intp.get_tensor(idx).squeeze() for idx in self.output_idxs] boxes = [(t*rh, l*rw, b*rh, r*rw) for (t, l, b, r) in boxes] # scale the coords back return list(zip(boxes, label_id, conf)) def run(self): while not self.stop_event: ret, img = self.webcam.read() if not ret: #re-open camera if read fails. Useful
2025-04-05🐛 BugI think it's a small problem but I still can't future it out ..I want to accomplish inference feature using libtorch and OpenCV . So I downloaded the last libtorch(GPU) from Pytorch.org. And also build OpenCV(4.0.0) from source.When I build libtorch app and OpenCV app with cmake independently, it succeeds.And when I build libtorch and OpenCV together and don't use 'imread()' function,it succeeds. And the code works in GPU(speed faster than CPU):#include "torch/script.h"#include "torch/torch.h"#include #include #include using namespace std;using namespace cv;int main(int argc, const char* argv[]){ if (argc != 2) { std::cerr \n"; return -1; } std::shared_ptr module = torch::jit::load(argv[1]); std::vector inputs; inputs.push_back(torch::ones({1,3,224,224}).to(at::kCUDA)); module->to(at::kCUDA); // inputs.at[0].to(at::kCUDA); double timeStart = (double)getTickCount(); for(int i = 0 ; i forward(inputs).toTensor(); double nTime = ((double)getTickCount() - timeStart) / getTickFrequency(); cout #include opencv2/opencv.hpp>#include "torch/script.h"#include "torch/torch.h"#include iostream>#include memory>#include ctime>using namespace std;using namespace cv;int main(int argc, const char* argv[]){ if (argc != 2) { std::cerr "usage: example-app \n"; return -1; } std::shared_ptr module = torch::jit::load(argv[1]); std::vector inputs; inputs.push_back(torch::ones({1,3,224,224}).to(at::kCUDA)); module->to(at::kCUDA); // inputs.at[0].to(at::kCUDA); double timeStart = (double)getTickCount(); for(int i = 0 ; i 1000 ; i++) at::Tensor output = module->forward(inputs).toTensor(); double nTime = ((double)getTickCount() - timeStart) / getTickFrequency(); cout "Time used:" 1000 " ms" the CMakeLists:cmake_minimum_required(VERSION 3.12 FATAL_ERROR)project(simnet)find_package(Torch REQUIRED)find_package(OpenCV REQUIRED)if(NOT Torch_FOUND) message(FATAL_ERROR "Pytorch Not Found!")endif(NOT Torch_FOUND)message(STATUS "Pytorch status:")message(STATUS " libraries: ${TORCH_LIBRARIES}")message(STATUS "OpenCV library status:")message(STATUS " version: ${OpenCV_VERSION}")message(STATUS " libraries: ${OpenCV_LIBS}")message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")add_executable(simnet main.cpp)# link_directories(/usr/local/lib) 'find_package' has already done thistarget_link_libraries(simnet ${TORCH_LIBRARIES} ${OpenCV_LIBS})set_property(TARGET simnet PROPERTY CXX_STANDARD 11)and cmake config:/home/prototype/Downloads/clion-2018.3/bin/cmake/linux/bin/cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_PREFIX_PATH=/home/prototype/Desktop/Cuda-project/libtorch -G "CodeBlocks - Unix Makefiles" /home/prototype/CLionProjects/simnet-- The C compiler identification is GNU 7.3.0-- The CXX compiler identification is GNU 7.3.0-- Check for working C compiler: /usr/bin/cc-- Check for working C compiler: /usr/bin/cc -- works-- Detecting C compiler ABI info-- Detecting C compiler ABI info - done-- Detecting C compile features-- Detecting C compile features - done-- Check for working CXX compiler: /usr/bin/c++-- Check for working CXX compiler: /usr/bin/c++ -- works-- Detecting CXX compiler ABI info-- Detecting CXX compiler ABI info - done-- Detecting CXX compile features-- Detecting CXX compile features - done-- Looking for pthread.h-- Looking for pthread.h - found-- Looking for pthread_create-- Looking for pthread_create -
2025-03-31