OpenCV Error: src.cols > 0 && src.rows > 0 in function 'warpAffine'

109 views Asked by At

I am working on rotating the images by 5 degree using below OpenCV Python code:

def rotate_image(image, angle):
    (h, w) = image.shape[:2]
    center = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D(center, -angle, 1.0)
    rotated_image = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
    return rotated_image

It works fine for most of the images but for some of the images, it shows below error:

OpenCV(4.6.0) /io/opencv/modules/imgproc/src/imgwarp.cpp:2595: error: (-215:Assertion failed) src.cols > 0 && src.rows > 0 in function 'warpAffine'

I have checked the size of the image where this exception comes and it's all good. Why is this error happening?

1

There are 1 answers

3
toyota Supra On

Edit: Using OP's script.

Your code is working with no minor change. Using OpenCV 4.6.0.

Comment out #return rotated_image in rotate_image() function.

Snippet:

import cv2 as cv


def rotate_image(image, angle):

    img = cv.imread(image, cv.IMREAD_GRAYSCALE)
    (h, w) = img.shape[:2]
    center = (w // 2, h // 2)
    M = cv.getRotationMatrix2D(center, -angle, 1.0)
    rotated_image = cv.warpAffine(img, M, (w, h), flags=cv.INTER_CUBIC, borderMode=cv.BORDER_REPLICATE)
    #return rotated_image
    #cv.imwrite('rotate_image.jpg', rotated_image)
    cv.imshow('img', rotated_image)
 
rotate_image('w2.jpg', 90)

cv.waitKey(0)
cv.destroyAllWindows()

Screenshot:

enter image description here