Converting OpenCV code snippet from C++ to Python

Question:

I’m trying to convert this code to python.
can anyone help me?

    cv::Mat image;
while (image.empty()) 
{
    image = cv::imread("capture.jpg",1);
}
cv::imwrite("result.jpg",image);
`
Asked By: Ali Dhouib

||

Answers:

In Python the Mat of C++ becomes a numpy array and hence the image manipulation becomes as simple as accessing a multi dimensional array. However the methods name are same in both C++ and Python.

import cv2 #importing opencv module

img = cv2.imread("capture.jpg", 1) #Reading the whole image

cv2.imwrite("result.jpg", img) # Creating a new image and copying the contents of img to it

EDIT: If you want to write the contents as soon as the image file is being generated then you can use os.path.isfile() which return a bool value depending upon the presence of a file in the given directory.

import cv2 
import os.path

while not os.path.isfile("capture.jpg"):
    #ignore if no such file is present.
    pass

img = cv2.imread("capture.jpg", 0)

cv2.imwrite("result.jpg", img)

You can also refer to docs for detailed implementation of each method and basic image operations.

Answered By: ZdaR
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.