<jupyter_start><jupyter_text>Create class specific datasetsImages are cropped to bbox, sized specifically to 200x200 for input<jupyter_code>import os
import imutils
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Pyimage search DL4CV, "Practioners Bundle", chapter 2
# import the necessary packages
import imutils
import cv2

class AspectAwarePreprocessor:
    def __init__(self, width, height, inter=cv2.INTER_AREA):
        # store the target image width, height, and interpolation
        # method used when resizing
        self.width = width
        self.height = height
        self.inter = inter
        
    def pad_to_square(self,image):
        (w,h) = image.shape[:2]
        w_pad = (h-w)// 2 if h > w else 0
        h_pad = (w-h)// 2 if w > h else 0
        imagePad = cv2.copyMakeBorder(image,w_pad,w_pad,h_pad,h_pad,cv2.BORDER_CONSTANT,value=[0,0,0])
        #print(f"Image height={h}\nImage widt={w}")
        #print(f"This is crop width={w_pad}\nThis is crop height={h_pad}")
        return imagePad
    
    def crop_to_square(self,image,bbox):
        w,h = image.shape[:2]
        wBB,hBB = bbox[2]-bbox[0],bbox[3]-bbox[1]
        dW = (hBB-wBB) // 2 if hBB > wBB else 0
        dH = (wBB-hBB) // 2 if wBB > hBB else 0
        cropBB = [max(bbox[0]-dW,0),
                  max(bbox[1]-dH,0),
                  min(bbox[2]+dW,w),
                  min(bbox[3]+dH,h)]
        imgCrop = image[cropBB[1]:cropBB[3],cropBB[0]:cropBB[2],:]
        return imgCrop
        

    def preprocess(self, image,bbox=None,pad_to_square=False,crop_to_square=False):
        if bbox is not None:
            assert type(bbox) is tuple or \
                   type(bbox) is list  and \
                   len(bbox) == 4, \
                    "Invalid object supplied for bbox. Should be 4-tpl"
        if pad_to_square: image = self.pad_to_square(image)
        if crop_to_square: image = self.crop_to_square(image,bbox)
        # grab the dimensions of the image and then initialize
        # the deltas to use when cropping
        (h, w) = image.shape[:2]
        dW = 0
        dH = 0

        # if the width is smaller than the height, then resize
        # along the width (i.e., the smaller dimension) and then
        # update the deltas to crop the height to the desired
        # dimension
        if w < h:
            image = imutils.resize(image, width=self.width,
                inter=self.inter)
            dH = int((image.shape[0] - self.height) / 2.0)

        # otherwise, the height is smaller than the width so
        # resize along the height and then update the deltas
        # crop along the width
        else:
            image = imutils.resize(image, height=self.height,
                inter=self.inter)
            dW = int((image.shape[1] - self.width) / 2.0)

        # now that our images have been resized, we need to
        # re-grab the width and height, followed by performing
        # the crop
        (h, w) = image.shape[:2]
        image = image[dH:h - dH, dW:w - dW]

        # finally, resize the image to the provided spatial
        # dimensions to ensure our output image is always a fixed
        # size
        return cv2.resize(image, (self.width, self.height),
            interpolation=self.inter)
#testImage = '../data/testImgClasses/Dress.jpg'
testImage = '../data/testImgClasses/Jeans.jpg'
pp = AspectAwarePreprocessor(200,200)
imgOrig = plt.imread(testImage)
#imgOrig = cv2.imread(testImage)
imgResize = pp.preprocess(imgOrig)
imgOrig.shape
ax0 = plt.subplot(1,2,1)
ax0.imshow(imgOrig)

ax1 = plt.subplot(1,2,2)
ax1.imshow(imgResize)
#bb = [100,50,225,150]   # square shape
bb = [125,50,225,200]   # rectangular shape
imgCrop = imgOrig[bb[1]:bb[3],bb[0]:bb[2],:]
#imgCrop = pp.preprocess(imgCrop)
imgPatch = patches.Rectangle(xy=(bb[0],bb[1]),
                             width=bb[2]-bb[0],
                             height=bb[3]-bb[1],
                             fill=False,
                             linestyle='-',color='pink')
ax0 = plt.subplot(1,2,1)
ax0.add_patch(imgPatch)
ax0.imshow(imgOrig)

ax1 = plt.subplot(1,2,2)
ax1.imshow(imgCrop)
imgSquare = pp.pad_to_square(imgCrop)
ax0 = plt.subplot(1,2,1)
ax1 = plt.subplot(1,2,2)
ax0.imshow(imgSquare)
ax1.imshow(pp.preprocess(imgCrop))
w,h = imgOrig.shape[:2]
wBB,hBB = bb[2]-bb[0],bb[3]-bb[1]
dW = (hBB-wBB) // 2 if hBB > wBB else 0
dH = (wBB-hBB) // 2 if wBB > hBB else 0


cropBB = [max(bb[0]-dW,0),
          max(bb[1]-dH,0),
          min(bb[2]+dW,w),
          min(bb[3]+dH,h)]
cropBB          
imgCropSquare = imgOrig[cropBB[1]:cropBB[3],cropBB[0]:cropBB[2],:]
#imgCrop = pp.preprocess(imgCrop)
plt.imshow(imgCropSquare)
imgAdj=pp.preprocess(imgCropSquare)
plt.imshow(imgAdj)
imgAdj.shape
imgAdj2 = pp.preprocess(imgOrig,crop_to_square=True,bbox=bb)
plt.imshow(imgAdj2)
help(plt.imsave)<jupyter_output>Help on function imsave in module matplotlib.pyplot:

imsave(fname, arr, **kwargs)
    Save an array as in image file.
    
    The output formats available depend on the backend being used.
    
    Parameters
    ----------
    fname : str or file-like
        The filename or a Python file-like object to store the image in.
        The necessary output format is inferred from the filename extension
        but may be explicitly overwritten using *format*.
    arr : array-like
        The image data. The shape can be one of
        MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
    vmin, vmax : scalar, optional
        *vmin* and *vmax* set the color scaling for the image by fixing the
        values that map to the colormap color limits. If either *vmin*
        or *vmax* is None, that limit is determined from the *arr*
        min/max value.
    cmap : str or `~matplotlib.colors.Colormap`, optional
        A Colormap instance or registered colormap name. The colormap
        maps sca[...]
{'fraction_non_alphanumeric': 0.11700494627323896, 'fraction_numerical': 0.024731366194780828, 'mean_word_length': 2.457547169811321, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '391434', 'license': 'MIT', 'n_tokens_mistral': 2126, 'n_tokens_neox': 2055, 'n_words': 536, 'path': 'DeepFashionModel/classDetect/Trial_CropAndResizeImages.ipynb', 'repo_name': 'RexBarker/DeepF', 'size': '5863'}