<jupyter_start><jupyter_text>Imports<jupyter_code>import glob
import cv2
import skimage
from time import sleep
import skimage.io as io
import numpy as np
import commonfunctions as cf
from skimage.feature import hog
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn import svm
import matplotlib.pyplot as plt
from skimage.transform import rescale, resize, downscale_local_mean
from sklearn import metrics
import pickle<jupyter_output>/home/mohamed/.local/lib/python3.8/site-packages/skimage/io/manage_plugins.py:23: UserWarning: Your installed pillow version is < 8.1.2. Several security issues (CVE-2021-27921, CVE-2021-25290, CVE-2021-25291, CVE-2021-25293, and more) have been fixed in pillow 8.1.2 or higher. We recommend to upgrade this library.
  from .collection import imread_collection_wrapper<jupyter_text>Loading Model<jupyter_code>loaded_model = pickle.load(open('car_detect_model2.sav', 'rb'))<jupyter_output>/home/mohamed/.local/lib/python3.8/site-packages/sklearn/base.py:329: UserWarning: Trying to unpickle estimator SVC from version 0.24.1 when using version 1.0.2. This might lead to breaking code or invalid results. Use at your own risk. For more info please refer to:
https://scikit-learn.org/stable/modules/model_persistence.html#security-maintainability-limitations
  warnings.warn(<jupyter_text>Function to preprocess image before passing to model<jupyter_code>def preprocess_image(image): 
    '''
    Function takes the BGR image and return the histogram of its RGB image

    Parameters
    ------------
    image : 3d matrix of a bgr image

    Returns
    --------
    The hog features of the rgb image

    '''
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = skimage.transform.resize (image, 
                        (64, 64),
                        anti_aliasing=True)
    hog_features,_= hog(image, orientations=9,
                    pixels_per_cell=(8, 8),
                    cells_per_block=(3, 3), block_norm='L2-Hys', 
                    visualize=True, transform_sqrt=False,
                    feature_vector=True, multichannel=True)
    return hog_features
    pass<jupyter_output><empty_output><jupyter_text>Code to take the hog image and return whether it is car or not<jupyter_code>def isCar(image):
    '''
    function to use the loaded SVM model to dedtect whether picture is car or not
    
    Parameters
    ------------
    image : 3d matrix of a bgr image

    Returns
    -------

    iscar : Boolean      true if car flase if not
    '''
    hog_features=preprocess_image(image)
    X_test=[]
    X_test.append(hog_features)
    iscar=np.uint8(loaded_model.predict(X_test)[0])
    return iscar<jupyter_output><empty_output><jupyter_text>block to test the model and preprocess funciton<jupyter_code>img = cv2.imread('car7.png', -1)
print("result=",isCar(img))<jupyter_output>result= 1<jupyter_text>Extracting region of interest and classify it using the model---------------------------------------------------------------------<jupyter_code># load a video
video = cv2.VideoCapture('trimmed2.mp4')

# You can set custom kernel size if you want.
kernel = None

# Initialize the background object.
backgroundObject = cv2.createBackgroundSubtractorMOG2(varThreshold=10,detectShadows = True)

while True:
    
    # Read a new frame.
    ret, frame = video.read()

    # Check if frame is not read correctly.
    if not ret:
        break

    # Apply the background object on the frame to get the segmented mask. 
    fgmask = backgroundObject.apply(frame)
    #initialMask = fgmask.copy()
    
    # Perform thresholding to get rid of the shadows.
    _, fgmask = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY)
    #noisymask = fgmask.copy()
    
    # Apply some morphological operations to make sure you have a good mask
    fgmask = cv2.erode(fgmask, kernel, iterations = 1)
    fgmask = cv2.dilate(fgmask, kernel, iterations = 2)
    
    # Detect contours in the frame.
    contours, _ = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    # Create a copy of the frame to draw bounding boxes around the detected cars.
    frameCopy = frame.copy()
    #sleep(0.05)
    # loop over each contour found in the frame.
    bounded_img=frame
    frameCopy2=frame.copy()
    for cnt in contours:
        
        # Make sure the contour area is somewhat higher than some threshold to make sure its a car and not some noise.
        if cv2.contourArea(cnt) > 400:
            try:

                # Retrieve the bounding box coordinates from the contour.
                x, y, width, height = cv2.boundingRect(cnt)
                bounded_img=frameCopy2[x+40:x+width,y:y+height-10,:]
                boundedd_img2=skimage.transform.resize(bounded_img, 
                            (128, 128),
                            anti_aliasing=True)
                #cv2.imshow('initial Mask', boundedd_img2)
                if(isCar(bounded_img) or False):
                    #cv2.imshow('initial Mask', bounded_img)
                    # Draw a bounding box around the car.
                    cv2.rectangle(frameCopy, (x , y), (x + width, y + height),(0, 0, 255), 2)
                    
                    # Write Car Detected near the bounding box drawn.
                    cv2.putText(frameCopy, 'Car Detected', (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0,255,0), 1, cv2.LINE_AA)
            except:
                pass
    
    # Extract the foreground from the frame using the segmented mask.
    foregroundPart = cv2.bitwise_and(frame, frame, mask=fgmask)
        
    # Stack the original frame, extracted foreground, and annotated frame. 
    stacked = np.hstack((frame, foregroundPart, frameCopy))

    # Display the stacked image with an appropriate title.
    cv2.imshow('Original Frame, Extracted Foreground and Detected Cars', cv2.resize(stacked, None, fx=0.5, fy=0.5))
    #cv2.imsh

    # Wait until a key is pressed.
    # Retreive the ASCII code of the key pressed
    k = cv2.waitKey(1) & 0xff
    
    # Check if 'q' key is pressed.
    if k == ord('q'):
        
        # Break the loop.
        break

# Release the VideoCapture Object.
video.release()

# Close the windows.q
cv2.destroyAllWindows()
#            image_to_pass=frameCopy[x:x+width,y:y+width,:]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10145156200694225, 'fraction_numerical': 0.025086778163458504, 'mean_word_length': 2.689755529685681, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 1, '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': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '231815', 'license': 'MIT', 'n_tokens_mistral': 2070, 'n_tokens_neox': 1917, 'n_words': 568, 'path': 'integration.ipynb', 'repo_name': 'MohamedElhadidy0019/Vehicle_Detection', 'size': '6338'}