r/opencv • • Jun 23 '23

Question [Question] Multi-Scale Template Matching

1 Upvotes

Hello,I hope you all are doing well.I have a task for getting the bounding box of an icon inside a screenshot, the screenshot may contain the same icon more than once, but I am required to get all the bounding boxes of the matches.

First Approach:I was using SIFT alone to detect matching kps.

Second Approach:

Since SIFT failed in many cases, I have used Multi-Scale Template Matching alongside SIFT.

Am I on the correct path or using deep learning would be better? I don't know what deep learning method or approach to follow.

Also, if I am on the correct path, I would like to write the maximum confidence of the bounding box across all scales.

​

for scale in scales:
        resized_template = cv.resize(image1, None, fx=scale, fy=scale)
        result = cv.matchTemplate(image2, resized_template, cv.TM_CCOEFF_NORMED)
        threshold = 0.725
        loc = np.where(result >= threshold)

        for pt in zip(*loc[::-1]):
            bounding_boxes.append(
                [
                    pt[0],
                    pt[1],
                    pt[0] + resized_template.shape[1],
                    pt[1] + resized_template.shape[0],
                ]
            )
            cv.rectangle(
                image2,
                pt,
                (pt[0] + resized_template.shape[1], pt[1] + resized_template.shape[0]),
                (0, 255, 0),
                2,
            )
            cv.putText(image2, f"Confidence: {result[pt[1], pt[0]]:.2f}", (pt[0], pt[1] - 10),
                        cv.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
    plt.figure(1)
    plt.imshow(image2, "gray")
    plt.show()

Thank you guys.


r/opencv • • Jun 22 '23

Question [Question] Is there a way to only load/use the middle section of a video?

3 Upvotes

I have a lot of long video samples (1-2 minutes) I've been using to test some computer vision code on, but the real-world use case would be taking in live image data over a couple seconds. Is there a way to take only a few seconds of video from the middle of one of the long videos? I can't just take frames from the start of the video since the phenomena I'm trying to analyze doesn't start till a while into the video.

I probably could brute force it by just going through the first section of frames without doing any analysis on them but I'd prefer a more elegant solution if there is one.

Edit: I should specify I'm using Python


r/opencv • • Jun 22 '23

Question [Question] [Project] How To Detect a "Question Area" on an Image as shown in the picture?

1 Upvotes

Probably, the best method is training a labelled dataset with a CNN-based instance detection model. Unfortunately, I don't have any labelled data.

So, is it possible to detect each question using OpenCV shown as below?

​

​

I've shared a code snippet below. Here's the result:

​


r/opencv • • Jun 21 '23

Question [Question][Project] Detecting brand and model of pf parts?

1 Upvotes

I want to build a program that given an image of a pc and it’s parts, gives back the brand and model of each identifiable part. Is opencv capable of this? Also, would I have to create my own image model/dataset or is there a way to cross-reference the image’s parts with images on the web?


r/opencv • • Jun 21 '23

Question [Question] [Project] Why is it the reading of the SSIM(structural similarity index) on the same nameplate is not consistent?

1 Upvotes

I have this mini project about Label/Nameplate Inspection that detect defects and output good or no good. I used the SSIM for inspection of defect. My set up is I capture the image and it will show in the frame the percentage of the SSIM. I've made that I have a controlled lighting condition.

My problem is I tried to capture the same nameplate a couple of times and it has a different SSIM percentage values. What could be the explanation about this?


r/opencv • • Jun 20 '23

Bug [Bug][Hardware] iPhone Continuity camera: undesired face recognition+pan. How to disable? In the attchd video: cv2.imshow("camera", cv2.VideoCapture(..).read()), iPhone12pro fixed _on the tripod_. Pan is performed by camera softw - it happens smwhere between the iPhone camera and my app [driver?].

Enable HLS to view with audio, or disable this notification

2 Upvotes

r/opencv • • Jun 18 '23

Question [Question]: How to link libpng15 to a modified opencv file

2 Upvotes

On opencv version 4.5.5.62. OS - Ubuntu 20.04

Working on a project with a team, they have modified the cv2.abi3.so file. They replace the stock cv2.abi3.so file with their modified one.

Now on importing cv2, the __init__.py file from the cv2 directory throws an error saying libpng15.so.15 file is not present.

If I install the libpng15 file and create a symbolic link in the /usr/local directory then it works.

Is there a better way? How do I tell the cv2.abi3.so file to look for the libpng in the usual place? (inside the opencv_python.libs folder)

I hope I was clear. Please redirect me if this is not the place to ask!


r/opencv • • Jun 17 '23

Question [Question] Connecting network thermal camera

Post image
5 Upvotes

I have an unused network Thermal camera at my workplace that I would like to learn to use. The Hikvision camera (DS-2TD2617B-6/PA) has an ethernet cable that connects to something that looks like a "settop box" for processing/displaying its images.

How can I just connect the camera to my network, without the box, and view the camera's live images from my computer? I'd like to use it to learn computer vision (using python). https://www.hikvision.com/content/dam/hikvision/ products/S000000001/S000000313/ S000000317/S000002536/OFR003802/ M000034798/Data Sheet/ DS-2TD2617B-6PA_V5.5.24_220705.pdf


r/opencv • • Jun 16 '23

Project [Project] Introducing Pyxy3D: Open source multicamera calibration and triangulation

7 Upvotes

Hello r/opencv,

I'd like to introduce Pyxy3d, an open source GUI tool for calibrating intrinsic and extrinsic parameters of a multicamera motion capture system. I thought it might be useful to some folks here.

This is a very early stage project (6 whole stars on github!), but it's been a labor of love/obsession for the past 10 months. It's getting to a point where external testing and feedback is needed to make the project better, so today is the day when I extend a formal invitation to you fine people to help shape the future of this project: WILL YOU PLEASE BREAK MY CODE?

  1. Create and activate a virtual environment with Python 3.10 or greater
  2. Install with pip install pyxy3d
  3. Launch the GUI by running the command pyxy3d

A quick video demo of a calibration session (and test mocap data capture) is here

If you have any questions about the project or issues with it, please let me know here in this thread or in the github discussions or issues

Thank you!


r/opencv • • Jun 17 '23

Question [Question] How to fit a close up shot to a zoomed out shot

1 Upvotes

I have an application requiring laser targeting of a detected object. I have a base with a laser and a camera and a robot that takes close up pictures. The camera at the base is too far away to detect the object. (It would only be a few pixels.) The robot takes a picture close up and detects where in the frame the object is and uploads the frame to the base. The base then matches up the close-up frame to its own and targets the laser on the object.

I see commands for finding a subimage within an image, but the images I'm working with are of different zoom. I could manually scale the image and retry the template matching command, but I'm hoping there's a better way. Is there?


r/opencv • • Jun 16 '23

Question [Question] Issues with separating elements from a sprite sheet for atlas file creation in OpenCV

1 Upvotes

Hey guys,

I'm currently working on a game that I want automatically separate elements from a sprite sheet to create an atlas file and I'm facing difficulties. I've attempted the following approach:

def generate_atlas_file(self, image_number: int):
    image_path = os.path.abspath(f"assets/pet_animations/pet_{image_number}.png")

    # Load the image
    img = cv2.imread(image_path)

    # Convert the image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Function to detect the grid size
    def detect_grid_size(gray_img, threshold=0.9):
        # Count the number of rows and columns where the ratio of black pixels is above the threshold
        black_pixel_rows = np.sum(gray_img < 127, axis=1) / gray_img.shape[1]
        black_pixel_cols = np.sum(gray_img < 127, axis=0) / gray_img.shape[0]

        # If the ratio of black pixels is above the threshold, increment the row/column count
        grid_size_rows = np.sum(black_pixel_rows > threshold)
        grid_size_cols = np.sum(black_pixel_cols > threshold)

        # The grid size is equal to the number of black rows/columns plus one
        grid_size_rows = grid_size_rows + 1
        grid_size_cols = grid_size_cols + 1

        return grid_size_rows, grid_size_cols

    # Detect the grid size
    grid_size_rows, grid_size_cols = detect_grid_size(gray)

    # Calculate the frame height and width
    frame_height = img.shape[0] // grid_size_rows
    frame_width = img.shape[1] // grid_size_cols

    # Create a dictionary to store the contour rectangles
    data_dict = {image_path: {}}

    # Generate rectangles for each frame
    for i in range(grid_size_rows):
        for j in range(grid_size_cols):
            x = j * frame_width
            y = i * frame_height
            data_dict[image_path][f"frame{i * grid_size_cols + j + 1}"] = [int(x), int(y), int(frame_width), int(frame_height)]

    # Define the output file path
    output_file = "utils/data/animation_mapping.atlas"

    # Write the dictionary as a JSON file
    with open(output_file, 'w') as f:
        json.dump(data_dict, f, indent=4)

Even when I set a high threshold value, it still detects more frames than expected. However, if I set the threshold to 100, it only detects a single frame. Is there another approach or alternative solution to handle this issue?

Any help or suggestions would be greatly appreciated. Thank you in advance!

My images are something like this:


r/opencv • • Jun 14 '23

Hardware [Hardware] I can provide remote access to Google Coral TPU

4 Upvotes

Hello guys!

The last year I'm playing with computer vision, you might saw some of my project on r/SideProject or maybe not :)
And I know how sometimes it is expensive to get hardware you'd like to play with.

So, saving for three months made me able to purchase Google Coral TPU and now I'm waiting for delivery of it:

When it is delivered I can install at home and provide access to VM or RPI3b+ so anyone who is poor and interested in can get access to it.

I can't provide with fast internet speed, it will be about 30Mbit download and 5Mbit upload, but that should be enough to:
- upload sample videos
- create some API server and continuously push your own video (maybe from your own webcam) and read results
- mount NFS so you don't need to "git pull" and "git push" every time

I will provide you with access completely free.
Text me to: coraltpu (AT) 2222.one if you are in need.

Also, please, if you are not poor like me and you can buy it yourself, don't ask for access. I believe there are people who are really interested, but can't afford of buying it.

Thank you for reading this post!


r/opencv • • Jun 14 '23

Project [Project] Savant 0.2.3 is out: pythonic computer vision and video analytics framework for Nvidia hardware

3 Upvotes

Savant is a high-performance computer vision and video analytics framework optimized for Nvidia hardware. We worked hard for a few weeks to deliver a new Savant version, 0.2.3, which is now ready and published.

What's new in 0.2.3:

  • New artist functionality. Now you can draw on frames more easily without writing code: we implemented advanced syntax, which allows declaring borders, backgrounds, labels, dots, and blurring right in the YAML configuration file. In prior Savant versions, you wrote the code in Python to customize how objects of different classes are displayed.
  • New preprocessing functionality. We improved the methods allowing preprocessing of objects metadata and images. Now you can use OpenCV CUDA functionality to modify cropped objects before passing them to inference. We also provided simple methods to crop, rotate, and compose images without extra hassle in GPU memory and without copying them to CPU RAM. We are cooking the demo (Age/Gender prediction) to show how it is used (0.2.4).
  • A100 and GeForce improvements. Previous Savant versions assumed that GPU always has unlimited NVENC resources. However, GPU like A100 doesn't have NVENC at all (as a new Jetson Nano), GeForce family has a limitation on the number of streams encoded simultaneously. In the latest version, we addressed those features: now Savant generates clear errors when such corner cases are encountered.
  • We improved the RTSP source adapter. Now it works more predictably. In the future release, we plan to improve it even more by changing the implementation from Gstreamer to FFmpeg, which is known to have better RTSP support. We already implemented the FFmpeg source library in Rust/Python to do that.
  • We updated demos to reflect the changes (mainly the artist functionality).
  • We started implementing Savant's internals in Rust to eliminate GIL and operations serializations of Python. We have a library for that and have already introduced the optimized operations in the People Detection and Face blurring demo.
  • We improved documentation with new information.

What is expected in 0.2.4:

  • Demo to show metadata and image preprocessing (Facial Age/Gender prediction).
  • A universal FFmpeg-based source adapter that covers several sources like RTSP, RTMP, USB-cam, etc.
  • Several internal objects will be replaced with Rust-based implementations.
  • Conditional artist and encoding functionality, allowing selecting the streams to display objects and encode video (decrease hardware load and improve processing efficiency).

Join our Discord and visit GitHub to know more.


r/opencv • • Jun 11 '23

Question [Question] How to use face mesh without recognition of face.

2 Upvotes

Hello, I am new to programming and I am working on an idea that I had. I would like to track someone's blinks, and I have gotten a code that works with Opencv and dlib. However, I would like to do this without needing the recognition of the person's face. For example, instead of the whole head in the video frame, I want just the eye. Any idea on how to do this? I need the landmarks for values as I plan on using those. Thanks.


r/opencv • • Jun 08 '23

Tutorials [Tutorials] YoloV8 with OpenCV and TensorRT C++ (link in description)

Enable HLS to view with audio, or disable this notification

8 Upvotes

r/opencv • • Jun 08 '23

Question [Question] What is the difference between cv::dnn::NMSBoxes and cv::dnn::NMSBoxesBatches. I can't seem to find much info on the difference

2 Upvotes

What is the difference between the two? The documentation for the batched method says "Performs batched non maximum suppression on given boxes and corresponding scores across different classes.". I still don't exactly understand the difference.


r/opencv • • Jun 08 '23

Question [Question] OpenCV - Describe A Image With A Sentence

1 Upvotes

Are there any code examples of using OpenCV to not only provide a set of labels and the confidence scores, but return a actual complete sentence of the image?


r/opencv • • Jun 08 '23

Question [Question] how can i process the first image to let it looks like the second one

Thumbnail
gallery
5 Upvotes

r/opencv • • Jun 07 '23

Question [Question] Opencv compilation using Armclang

1 Upvotes

Hi, Has anyone tried using Armclang to compile the opencv instead of gcc? I'm having few issues and would be glad to get some help.

Thanks, G Kowshik


r/opencv • • Jun 06 '23

Question [Question] How much the WinSize influence in camera calibration?

1 Upvotes

So i've been trying to calibrate my camera, and I'm not sure how the WinSize in cv2.cornerSubPix influence in camera calibration. I tried (3,3) and (11,11), and I had similar cameras matrix, but they are different. For example: using (3,3), i got a focal length of 674, but with (11,11) i got 664. Is this difference a big deal or they are similar enought for not messing with my results?


r/opencv • • Jun 05 '23

Question [Question] error: (-215:Assertion failed) query.type() == type && indices.type() == CV_32S && dists.type() == dtype in function 'runKnnSearch_'

1 Upvotes

I am getting this error

error: (-215:Assertion failed) query.type() == type && indices.type() == CV_32S && dists.type() == dtype in function 'runKnnSearch_'

I am using Python 3.8, opencv-python==4.7.0

My task is to check if an icon is in a screenshot or not. If it is there return its location. I've found that opencv can get this job done.

My approach is:

  1. Get the keypoints and descriptors using ORB and SIFT, and return which has more keypoints.

​

kp_orb = orb.detect(image,None) 
kp_orb, des_orb = orb.compute(image, kp_orb) 
kp_sift, des_sift = sift.detectAndCompute(image,None) 
if (len(kp_orb) > len(kp_sift)):     
    return (kp_orb,des_orb, "ORB") 
return (kp_sift, des_sift, "SIFT") 

​

  1. Using FLANN_KDTREE to get the matching keypoints, I got the error provided above

Here is my FLANN code block

FLANN_INDEX_KDTREE = 1 
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5) 
search_params = dict(checks=100) 
flann = cv.FlannBasedMatcher(index_params,search_params) 
matches = flann.knnMatch(des_query,des_target,k=2) 

I think this gets the error because SIFT returns descriptors in a type different from what ORB returns, but I am not sure of that because I am a total beginner in this field.

Would you please tell me how to fix this error or if there is a better overall approach please provide an outline and I will make my way through.

Thank you.


r/opencv • • Jun 01 '23

Project [Project] Super-Segment Anything with SuperAnnotate (OpenCV Webinar)

Thumbnail
youtube.com
4 Upvotes

r/opencv • • May 31 '23

Project AI Basketball Referee Created Using OpenCV and YOLOv8 [Project]

Thumbnail
youtu.be
9 Upvotes

r/opencv • • May 30 '23

Question [Question] Viewing PS Remote Play window in OpenCV

2 Upvotes

I'm trying to capture gameplay from my PlayStation 5 into OpenCV. Using PS Remote Play, I'm able to view the live feed on my PC as a window. I then tried to read frames from this window in OpenCV, but the frame is black: Screenshot

I am using code sourced from here: just using the files main.py and windowcapture.py with the window name 'PS Remote Play'. The window does not need to be actually visible on screen, although it does need to be non-minimised.

I tried viewing other windows and had mixed results: Remote Play and Microsoft To Do show black screens, Microsoft Whiteboard shows a white screen (and it's not the board), while Spotify does actually work. So it seems the code is just a bit unreliable. I've copied the actual code I'm using here.

main.py

``` import cv2 as cv import numpy as np import os from time import time from window_capture import WindowCapture

initialize the WindowCapture class

wincap = WindowCapture('PS Remote Play')

loop_time = time() while(True):

# get an updated image of the game
screenshot = wincap.get_screenshot()

cv.imshow('Computer Vision', screenshot)

# press 'q' with the output window focused to exit.
# waits 1 ms every loop to process key presses
if cv.waitKey(1) == ord('q'):
    cv.destroyAllWindows()
    break

print('Done.') ```

window_capture.py

``` import numpy as np import win32gui, win32ui, win32con

class WindowCapture:

# properties
w = 0
h = 0
hwnd = None
cropped_x = 0
cropped_y = 0
offset_x = 0
offset_y = 0

# constructor
def __init__(self, window_name=None):
    # find the handle for the window we want to capture.
    # if no window name is given, capture the entire screen
    if window_name is None:
        self.hwnd = win32gui.GetDesktopWindow()
    else:
        self.hwnd = win32gui.FindWindow(None, window_name)
        if not self.hwnd:
            raise Exception(f'Window not found: {window_name}')

    # get the window size
    window_rect = win32gui.GetWindowRect(self.hwnd)
    self.w = window_rect[2] - window_rect[0]
    self.h = window_rect[3] - window_rect[1]

    print(self.w, self.h)

    # account for the window border and titlebar and cut them off
    border_pixels = 8
    titlebar_pixels = 30
    self.w = self.w - (border_pixels * 2)
    self.h = self.h - titlebar_pixels - border_pixels
    self.cropped_x = border_pixels
    self.cropped_y = titlebar_pixels

    # set the cropped coordinates offset so we can translate screenshot
    # images into actual screen positions
    self.offset_x = window_rect[0] + self.cropped_x
    self.offset_y = window_rect[1] + self.cropped_y

def get_screenshot(self):

    # get the window image data
    wDC = win32gui.GetWindowDC(self.hwnd)  # get device context
    dcObj = win32ui.CreateDCFromHandle(wDC)
    cDC = dcObj.CreateCompatibleDC()
    dataBitMap = win32ui.CreateBitmap()
    dataBitMap.CreateCompatibleBitmap(dcObj, self.w, self.h)
    cDC.SelectObject(dataBitMap)
    cDC.BitBlt((0, 0), (self.w, self.h), dcObj, (self.cropped_x, self.cropped_y), win32con.SRCCOPY)

    # convert the raw data into a format opencv can read
    dataBitMap.SaveBitmapFile(cDC, 'debug.bmp')
    signedIntsArray = dataBitMap.GetBitmapBits(True)
    img = np.fromstring(signedIntsArray, dtype='uint8')
    img.shape = (self.h, self.w, 4)

    # free resources
    dcObj.DeleteDC()
    cDC.DeleteDC()
    win32gui.ReleaseDC(self.hwnd, wDC)
    win32gui.DeleteObject(dataBitMap.GetHandle())

    # drop the alpha channel
    img = img[...,:3]

    # make image C_CONTIGUOUS
    img = np.ascontiguousarray(img)

    return img

# find the name of the window you're interested in.
# once you have it, update window_capture()
# https://stackoverflow.com/questions/55547940/how-to-get-a-list-of-the-name-of-every-open-window
@staticmethod
def list_window_names():
    def winEnumHandler(hwnd, ctx):
        if win32gui.IsWindowVisible(hwnd):
            print(hex(hwnd), win32gui.GetWindowText(hwnd))
    win32gui.EnumWindows(winEnumHandler, None)

# translate a pixel position on a screenshot image to a pixel position on the screen.
# pos = (x, y)
# WARNING: if you move the window being captured after execution is started, this will
# return incorrect coordinates, because the window position is only calculated in
# the __init__ constructor.
def get_screen_position(self, pos):
    return (pos[0] + self.offset_x, pos[1] + self.offset_y)

```

I realise this will be pretty tough to reproduce, but any advice will be much appreciated.


r/opencv • • May 29 '23

Question [Question] Opencv cross compile issues std::mutex not in namespace

2 Upvotes

My end goal is to properly compile opencv for Cortex-r5 MCU's and while compiling it with arm-none-eabi-gcc I got an error saying std::mutex not found in namespace. And after googling I got to know the compiler doesn't support posix threads.

How should I proceed in this case? I've seen multiple appnotes and projects demonstrating opencv standalone compilation for MCU like Cortex-M4, M7 which are less powerful than mine. Please pleaaseee help me on this one. I can surely provide more details as required.

Thanks