Creating a new image by preserving the contents of a bounding box with OpenCV in Python

Currently, I am working on a code snippet that utilizes OpenCV to detect the largest contour or object within an image. The snippet successfully creates the bounding box, but I am looking for the best method to save this bounding box as a separate image file. Essentially, I want to extract and store the largest object within the image as a new JPEG file. Below is the code I have been experimenting with:

import numpy as np
import cv2

font = cv2.FONT_HERSHEY_SIMPLEX
lineType = cv2.LINE_AA

im = cv2.imread('test/originals/8.jpg')
im_ycrcb = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)

ball_ycrcb_mint = np.array([0, 90, 100],np.uint8)
ball_ycrcb_maxt = np.array([25, 255, 255],np.uint8)
ball_ycrcb = cv2.inRange(im_ycrcb, ball_ycrcb_mint, ball_ycrcb_maxt)
cv2.imwrite('test/outputs/output8.jpg', ball_ycrcb) # Second image
areaArray = []
count = 1

_, contours, _ = cv2.findContours(ball_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
    area = cv2.contourArea(c)
    areaArray.append(area)
    areaLargest = np.argmax(areaArray)
    areaLargestMax = max(areaArray)
    areaLargestCnt = contours[areaLargest]
    x, y, w, h = cv2.boundingRect(areaLargestCnt)
    roi = im[y:y+h, x:x+w]
    cv2.imwrite('test/contours.jpg', im)   
    if area == areaLargestMax and area > 10000:
        cv2.drawContours(im, contours, i, (255, 0, 0), 7)
        cv2.rectangle(im, (x, y), (x+w, y+h), (0,255,0), 7)



cv2.imwrite('test/outputs/output9.jpg', im)

Answer №1

If you want to save a specific rectangular region of interest as a separate image, you can achieve this by extracting the ROI and then using the imwrite function.

roi = image[y:y+h, x:x+w]
cv2.imwrite("ROI_image.jpg", roi)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to create a single hollow marker in a matplotlib plot?

Here is my code snippet: import numpy as np import matplotlib.pyplot as plt x = np.random.rand(5) y = np.random.rand(5) markerfacecolors = ['k','k','none','k','k'] plt.plot(x,y,'--o',markerface ...

Generating the Next Sequence Number in Python Using Pandas

Dealing with a dataframe df = pd.DataFrame([1,5,8, np.nan,np.nan], columns = ["UserID"]) I need to replace any np.nan values with subsequent numbers starting from the highest value + 1 The resulting df.UserID should look like this: [1, 5, 8, 9, 10] ...

I'm having trouble getting my web page to scroll down using selenium in python - what could be causing this

The code is designed to scroll to the bottom of a webpage, but it appears that initially it does move and then oldHeight and newHeight values do not update properly. I attempted to use various methods such as returning window innerheight and the Yoffset, ...

Retrieving information from Flask server using an Ajax request

Exploring Flask and Ajax, my server-side web application is meant to double and return a passed number. I adapted the code from the example on Flask's site, resulting in this Python snippet: from flask import Flask, request, jsonify # Initialize the ...

Looking to create N text files? You can easily accomplish this using np.savetxt

In order to complete my math assignment, I must create N slices and save them in separate TXT files. Each step of the process should be written to a new file. N=10 j=1 for i in range (1,N): df_step=df2 [j::N] j+=1 np.savetxt(r'c:\Data ...

Encountering issues during the installation of a software, specifically due to the absence of the module

Greetings! I am encountering an issue while attempting to install the photologue application. I am following the installation instructions diligently. ~/coffee$ python manage.py shell Python 2.6.1 (r261:67515, Mar 18 2009, 13:52:30) [GCC 4.1.2 20061115 ( ...

Is there a fast method to transform a collection of lists (such as the one generated by scipy.spatial.KDTree.query_ball_tree) into an array of pairs?

I am currently facing a challenge in finding an efficient way to convert a list of lists into an array of pairs. Each pair consists of the index of the list row as the first value and all values within that list row as the second value. If a row is empty, ...

In Python, learn how to use regex to add a hyphen between a letter and a number, as well as to delete a hyphen between two letters

I've been attempting to utilize regex on a string for the following transformations: If there is a hyphen - between two alphabets, the hyphen should be removed: For example, A-BA should become ABA; and A-B-BAB should become ABBAB If an alphabet a ...

Guide to inserting a line break in a cell within a CSV file using Python

When viewing the CSV editor in Vscode, it appears like this: this is one cell Here is my code snippet where I introduce line breaks: lista='' for i in value: lista = lista + i + '\n' stock_bodega.append(lista) re ...

Guide to automatically running a Chrome extension that interacts with the main webpage?

I am looking for a way to automate testing for a specific chrome extension. While I have successfully used selenium-python to automate tasks on the parent web-page, I am facing a challenge automating the chrome-extension itself. Selenium is not designed t ...

What is the reason that pygame.mixer.Sound().play() doesn't return a value?

As per the pygame documentation, calling pygame.mixer.Sound().play() is expected to return a Channel object, and indeed it does. However, on certain occasions, it appears to return None causing an error to occur immediately after: NoneType has no attribut ...

Using Python to deliver live streaming HLS API content directly from disk storage

After capturing videos with my camera, I use FFMPEG to segment them for HTTP Live Streaming and generate an m3u8 file along with corresponding ts files. Now, all the *.ts and *.m3u8 files are stored in my local folder, and my goal is to serve these files ...

The absence of the Django CSRF token has been detected

Inside the custom.js file, there is a function defined as shown below : function contactTraxio(fullname, telephone, email) { if (typeof(fullname)==='undefined') fullname = null; if (typeof(telephone)==='undefined') telephone = ...

Using the glob function to parse through several CSV files can sometimes lead to an unexpected order

I am facing a challenge where I need to read multiple CSV files in the correct sequential order. The files are named with numbers like "file_0.csv", "file_1.csv", "file_2.csv", and so on, created in that specific order. However, when my code runs, the fil ...

Disabling the inplace feature of the ReLU function

This code snippet modifies a pretrained model by setting the ReLU state to 'False'. It has been developed and tested with various architectural designs like vgg, resnet, densenet. However, I feel that there may be a more efficient way to write th ...

Create an item that functions in a similar manner to a slice

How can a class be modified to represent itself as a slice when necessary? An attempted solution: class MyThing(object): def __init__(self, start, stop, otherstuff): self.start = start self.stop = stop self.otherstuff = others ...

Steps for selecting the Check Interactions button with Selenium

My current project involves using the website drugs.com to check for interactions between two drugs. I have entered the names of two drugs into the search box on this site and I need to click on the "check interactions" button to view the interaction resul ...

Python WSGI for Remote Directory Listing

Currently serving as an Intern in an IT service, I have been tasked with developing a web-based application using Python that will operate on a Linux environment. This web app needs to be WSGI-compliant and strictly without the use of any framework. My cu ...

Python - Extracting text content with Selenium from a text node

When utilizing Selenium and Python to scrape data from a website, I often encounter unlabelled texts such as HZS stonks remaining.... These texts do not have any identifiable name or label that allows me to extract them: Although I can easily access eleme ...

The system encountered a Keyerror 255 while attempting to execute a pymysql.connect command

Below is the provided code snippet: import pymysql pymysql.connect( host='localhost', port=3306, user='root', password='iDontWannaSay', db='iDontWannaShow', charset='utf8' ) Accomp ...