Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • akhot2/group-01-phys371-sp2023
  • jl190/group-1-beetle-drone
2 results
Show changes
Showing
with 1492 additions and 0 deletions
File added
The different files and directories contain the images and code necessary to construct the western corn rootworm (WCR) simulated dataset using the images given in the [Roboflow dataset](https://universe.roboflow.com/wcr-beetle-detection/wcr-beetle-traps). The content of each file is summarized below.
- `beetles`: Directory of cropped WCR beetles taken from the cropped traps
- `cropped_imgs`: Directory of cropped traps, containing both WCR beetles and insects
- `imgs`: Directory of uncropped traps, containing both WCR beetles and insects
- `non_beetles`: Directory of cropped various insects, not including WCR beetles, taken from the cropped traps
- `SimData.ipynb`: Constructs the simulated dataset using the cropped traps, beetles, and insects in the various folders
- `autocrop.py`: Performs cropping of an image using Otsu's Method, cropping only one image. To crop an image, setup the required environment and run the following command:
```
python3 autocrop.py imgpath destpath [sensitivity=110] [debug=False]
```
The available options are:
```
imgpath path to image file
destpath path to destination file, including new filename
sensitivity sensitivity of foreground vs background
debug saves additional images to folder (polygon and mask of foreground pixels)
```
*Note*: To perform autocropping, delete lines 111 and 133. These were implemented to be able to be used in `transfer.py`.
- `autocrop_folder.py`: Performs cropping of an image using Otsu's Method, cropping a whole folder. To crop a folder, setup the required environment and run the following command:
```
python3 autocrop_folder.py imgfolder destfolder [sensitivity=110] [debug=False]
```
The available options are:
```
imgfolder path to the folder of images
destfolder path to destination folder
sensitivity sensitivity of foreground vs background
debug saves additional images to folder (polygon and mask of foreground pixels)
```
*Note*: When one file fails to autcrop due to needing a higher or lower sensitivity, the whole program stops. In this case, it is better to move it out of the folder and correctly crop it with a new sensitivity using `autocrop.py` and `debug=True`. Then, you can use `autocrop_folder.py` again.
This diff is collapsed.
File added
File added
File added
# https://stackoverflow.com/questions/60941012/how-do-i-find-corners-of-a-paper-when-there-are-printed-corners-lines-on-paper-i
from PIL import Image
import numpy as np
import cv2
import sys
# does not work with heif rn
def crop(img, sensitivity=110, debug=False):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Define lower and uppper limits of what we call "white-ish"
lower_white = np.array([0, 0, 255 - sensitivity])
upper_white = np.array([255, sensitivity, 255])
# Create mask to only select white
mask = cv2.inRange(hsv, lower_white, upper_white)
# Change image to green where we found white
nopole = img.copy()
nopole[mask > 0] = (76, 52, 40)
# convert img to grayscale
gray = cv2.cvtColor(nopole, cv2.COLOR_BGR2GRAY)
# blur image
blur = cv2.GaussianBlur(gray, (3,3), 0)
# do otsu threshold on gray image
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
# apply morphology
kernel = np.ones((7,7), np.uint8)
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
morph = cv2.morphologyEx(morph, cv2.MORPH_OPEN, kernel)
# get largest contour
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
area_thresh = 0
for c in contours:
area = cv2.contourArea(c)
if area > area_thresh:
area_thresh = area
big_contour = c
# draw white filled largest contour on black just as a check to see it got the correct region
page = np.zeros_like(img)
cv2.drawContours(page, [big_contour], 0, (255,255,255), -1)
# get perimeter and approximate a polygon
peri = cv2.arcLength(big_contour, True)
corners = cv2.approxPolyDP(big_contour, 0.04 * peri, True)
# enforce CCW starting at top-left indexing
avgx = np.mean(corners[:,0,0])
avgy = np.mean(corners[:,0,1])
while(corners[0,0,0] > avgx or corners[0,0,1] > avgy):
corners = corners[[1,2,3,0], :, :]
# draw polygon on input image from detected corners
polygon = img.copy()
cv2.polylines(polygon, [corners], True, (0,0,255), 1, cv2.LINE_AA)
# Alternate: cv2.drawContours(page,[corners],0,(0,0,255),1)
# for simplicity get average of top/bottom side widths and average of left/right side heights
# note: probably better to get average of horizontal lengths and of vertical lengths
width = 0.5*( (corners[3][0][0] - corners[0][0][0]) + (corners[2][0][0] - corners[1][0][0]) )
height = 0.5*( (corners[1][0][1] - corners[0][0][1]) + (corners[2][0][1] - corners[3][0][1]) )
width = np.int0(width)
height = np.int0(height)
# reformat input corners to x,y list
icorners = []
for corner in corners:
pt = [ corner[0][0],corner[0][1] ]
icorners.append(pt)
icorners = np.float32(icorners)
# get corresponding output corners from width and height
ocorners = [ [0,0], [0,height], [width,height], [width,0] ]
ocorners = np.float32(ocorners)
# get perspective tranformation matrix
M = cv2.getPerspectiveTransform(icorners, ocorners)
# do perspective
warped = cv2.warpPerspective(img, M, (width, height))
warped_rgb = cv2.cvtColor(warped, cv2.COLOR_BGR2RGB)
polygon_rgb = cv2.cvtColor(polygon, cv2.COLOR_BGR2RGB)
if not debug:
return warped_rgb
return warped_rgb, page, polygon_rgb
def cropFromFile(imgpath, destpath, sensitivity=110, debug=False):
img = cv2.imread(imgpath)
ret = crop(img, sensitivity, debug)
if not debug:
warped_rgb = ret
else:
warped_rgb, page, polygon_rgb = ret
Image.fromarray(page).save(destpath+"page.jpg")
Image.fromarray(polygon_rgb).save(destpath+"polygon.jpg")
Image.fromarray(warped_rgb).save(destpath)
'''
if len(sys.argv) < 3 or len(sys.argv) > 5 :
sys.print("Format: python3 autocrop.py imgpath destpath [sensitivity=110] [debug=False]")
exit(1)
if len(sys.argv) == 3:
cropFromFile(sys.argv[1], sys.argv[2])
elif len(sys.argv) == 5:
if sys.argv[4] == "True":
cropFromFile(sys.argv[1], sys.argv[2], int(sys.argv[3]), True)
else:
cropFromFile(sys.argv[1], sys.argv[2], int(sys.argv[3]), False)
else:
try:
cropFromFile(sys.argv[1], sys.argv[2], sensitivity=int(sys.argv[3]))
except ValueError:
if sys.argv[3] == "True":
cropFromFile(sys.argv[1], sys.argv[2], debug=True)
else:
cropFromFile(sys.argv[1], sys.argv[2], debug=False)
'''
\ No newline at end of file
This diff is collapsed.
crop/beetles/beetle0.png

18.3 KiB

This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.