PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label bounding-box. Show all posts
Showing posts with label bounding-box. Show all posts

Wednesday, July 27, 2022

[FIXED] How to crop multi images use list bounding box position in the file (python)?

 July 27, 2022     bounding-box, crop, image-processing, json, python     No comments   

Issue

I have a dataset of images.jpg and a file csv has values bounding box position is top, left, right, bottom. I use ubuntu OS and the python language.


Solution

Something like this should work. It assumes a few things:

  • that the separator in your CSV is a semi-colon, i.e. ;
  • that your CSV file is called images.csv
  • that you want the cropped images output to a sub-directory called output
  • that you have PIL/Pillow installed, though it could easily be adapted to use pyvips, OpenCV, skimage

#!/usr/bin/env python3

import os
import re
import csv
import json
from PIL import Image

def cropImage(filename,coords):
    """Crop image specified by filename to coordinates specified."""
    print(f"DEBUG: cropImage({filename},{coords})")

    # Open image and get height and width
    im = Image.open(filename)
    w, h = im.width, im.height

    # Work out crop coordinates, top, left, bottom, right
    l = int(coords['left']  * w)
    r = int(coords['right'] * w)
    t = int(coords['top']   * h)
    b = int(coords['bottom']* h)

    # Crop and save
    im = im.crop((l,t,r,b))
    im.save("output/" + filename)
    return

# Create output directory if not existing
if not os.path.exists('output'):
    os.makedirs('output')

# Process CSV file - expected format
# heading;heading
# 00000001.jpg?sr.dw=700;{'right': 0.9, 'bottom': 0.8, 'top': 0.1, 'left': 0.2}
# 00000002.jpg?sr.dw=700;{'right': 0.96, 'bottom': 0.86, 'top': 0.2, 'left': 0.25}

with open('images.csv') as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=';')
    for row in csv_reader:
        fieldA, fieldB = row[:2]

        # Ignore header lines
        if not "jpg" in fieldA:
            continue

        # Strip trailing rubbish off filename
        filename = re.sub("\?.*","",fieldA)
        print(f"DEBUG: filename={filename}")

        # Replace single quotes in JSON with double quotes
        JSON = fieldB.replace("'",'"')
        print(f"DEBUG: JSON={JSON}")
        coords = json.loads(JSON)
        print(f"DEBUG: coords={coords}")

        cropImage(filename, coords)


Answered By - Mark Setchell
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 26, 2022

[FIXED] How to make crops from list of lists

 July 26, 2022     bounding-box, crop, numpy, opencv, python     No comments   

Issue

I have a list of n lists like this

pixels = [[400, 220, 515, 293], [433, 373, 482, 452], [401, 370, 477, 475]]

Each sublist correspond to the Top Left and Bottom Right Points for each crop

I made this code to extract a single crop from the whole list

  x1 = min(map(lambda x: x[0], pixels))
  y1 = min(map(lambda x: x[1], pixels))
  x2 = max(map(lambda x: x[2], pixels))
  y2 = max(map(lambda x: x[3], pixels))

  crop = img[y1:y2, x1:x2]
 cv2_imshow(crop)

How can I make n crops from n sublists?


Solution

Hope It will work

import cv2
pixels = [[400, 220, 515, 293], [433, 373, 482, 452], [401, 370, 477, 475]]
for i in pixels:
    img = cv2.imread(r"img _path")
    x1,y1,x2,y2 = i
    crop = img[y1:y2, x1:x2]


Answered By - Parthiban Marimuthu
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to crop and store bounding box image regions in Python?

 July 26, 2022     bounding-box, crop, opencv, python     No comments   

Issue

enter image description here

My idea is to use the multiple bounding box coordinates of the abnormal regions for a given image and crop these regions to save to a separate folder. I have written the code as shown below, to crop these multiple bounding box coordinates for a single image, however,I also get the bounding box which I have to get rid of.

import pandas as pd
import cv2
import numpy as np

df = pd.read_csv('excel1.csv')
image = cv2.imread('image2.png')
im_name = 'image2.png'

for i in range(len(df)):
    name = df.loc[i]['filename']
    if name == im_name:
        start_point = (df.loc[i]['x'],df.loc[i]['y'])  
        end_point = (df.loc[i]['x']+df.loc[i]['width'],df.loc[i]['y']+df.loc[i]['height'])  
        color = (128, 0, 0)  
        thickness = 2  
        image = cv2.rectangle(image, start_point, end_point, color, thickness) 
        crop = image[df.loc[i]['y']:df.loc[i]['y']+df.loc[i]['height'],
                     df.loc[i]['x']:df.loc[i]['x']+df.loc[i]['width']]
        cv2.imwrite("cropped/crop_{0}.png".format(i), crop)  
cv2.imwrite('bb.png', image)

Solution

Use numpy slicing in the loop and then Python/OpenCV imwrite() that crop also inside the loop with a different name for each iteration of the loop

crop = image[ystart:ystop, xstart:xstop]
cv2.imwrite("crop_{0}.png".format(i), crop)


You can also add a different path for each image you want to write if you want them to go to different folders.

For numpy slicing, see https://www.w3schools.com/python/numpy_array_slicing.asp



Answered By - fmw42
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing