Mujtaba Faizi
Mujtaba Faizi

Reputation: 339

Passing an image as an argument to a function in python

How can I create a function that takes an image file (not image filename) in python. Simply, like the following:

FaceController.py

import cv2
from Computer_Vision import Face_Detector as FD


def detectface():
    img = cv2.imread('DSC_1902.JPG')
    FD.detect(img)


detectface()

Face_Detector.py

import cv2

def detect(img):
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    cv2.namedWindow('img',cv2.WINDOW_NORMAL)
    cv2.imshow('img', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    cv2.imwrite('messigray.png', img)
    return img

Error:

OpenCV Error: Assertion failed (!empty()) in cv::CascadeClassifier::detectMultiScale, file C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp, line 1698
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    cv2.error: C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1698: error: (-215) !empty() in function cv::CascadeClassifier::detectMultiScale

Upvotes: 4

Views: 13468

Answers (2)

Vince Hall
Vince Hall

Reputation: 44

You can actually pass the image as a tensor. with cv2.imread() and torch. Which is easy, useful.

short answer: load with cv2.imread() transform to tensor with img = torch.Tensor(img)/255.

That works for my application. Yours might be a little different.

Code answer:

from Computer_Vision import Face_Detector as FD

def detectface():
  import cv2 
  import torch
  
  folder = r"This Folder/"
  image_file = folder+"image.png"
  # or 
  # file = r"image.png"
  # image_file = os.path.join(folder, file)
  img = imread(image_file)
  
  img = torch.Tensor(img)/255. # THE KEY LINE HERE.

   FDdetect(img):
     """Do stuff with object detection..."""
     result = 
     return result

Upvotes: 0

Abhishek Chatterjee
Abhishek Chatterjee

Reputation: 338

You can pass a pointer pointing to the image instead of the image or the filename of the image

EDIT

def image_function(imagePointer):
    #DO SOMETHING WITH THE IMAGE

#HERE IS THE IMAGE POINTER
image = open('your_image.png')

#CALLING THE FUNCTION
image_function(image)

Sorry, I don't know opencv so I can not help in your code :(

Upvotes: 1

Related Questions