Use opencv in python with gpu support to rotate images - python

I have compiled opencv 4.6.0 from source files with the cuda support. I have followed the guide for windows 10
The process is completed and I can see my gpu. I want to rotate an image by using GPU. In other words I have this simple code
import cv2
img = cv2.imread("cat.3.jpg")
a = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
cv2.imshow("cat", a)
cv2.waitKey(0)
It works fine, but on CPU. I want a similar code in Python that runs on GPU. A similar solution presented here
for C++.

I have found the solution. This is the code that I have developed
import cv2
import cv2.cuda as cuda
image = cv2.imread("myimage.jpg")
# Storing the image on GPU
src = cv2.cuda_GpuMat()
src.upload(image)
# Applying the rotation
a = cv2.cuda.rotate(src=src, dsize = (414,500), angle = 12, xShift= 0, yShift=0, interpolation=cv2.INTER_NEAREST)
# Downloading the image from GPU and visualizing the image
result = a.download()
cv2.imshow("cat", result)
cv2.waitKey(0)

Related

reproduce same output with scikit-image resize and OpenCV resize function

I'm trying to reproduce the same output with these snippets:
Scikit-Image + Keras
from keras.models import model_from_json
import numpy as np
from skimage.io import imread
from skimage.transform import resize
image = resize(imread(img_path, as_grey=False), (80, 80), preserve_range=True, mode='constant')
image /= 255.
img_array = np.array([image])
pred_IN = model.predict(img_array)
OpenCV
import cv2
model = cv2.dnn.readNet('mynet.prototxt', 'mynet.caffemodel')
image = cv2.imread(image_path)
img = cv2.dnn.blobFromImage(image, scalefactor=(1.0/255.0), size=(80, 80), swapRB=True, crop=False)
model.setInput(img)
pred = model.forward()
The problem is that I cannot get the same data to pass to the network (DNN module in case of OpenCV). Network is the same, input data is the same, but the results is slightly different and the reason is that resize function behaves differently between scikit-learn and OpenCV (used internally by blobFromImage) and don't know how to adapt the OpenCV code to match scikit-learn.
My final application will use OpenCV in C++, so I need to match this snippets, as my network has been trained with data generated by scikit-learn.
I think the reason is skimage use antialiasing (gaussian blur from scipy.ndimage before rescale) by default. You can achieve similar result wit resize in OpenCV by blurring your image (e.g. using cv2.GaussianBlur) before cv2.resize. Result from resize is not the same but with proper blur kernel size is very very similar (almost identical). Hope it'll help :)

Jupyter kernel crashes when trying to display image with OpenCV

I'm trying to run the example from here
import cv2
def viewImage(image):
cv2.namedWindow('Display', cv2.WINDOW_NORMAL)
cv2.imshow('Display', image)
print('test')
cv2.waitKey(0)
cv2.destroyAllWindows()
def grayscale_17_levels (image):
high = 255
while(1):
low = high - 15
col_to_be_changed_low = np.array([low])
col_to_be_changed_high = np.array([high])
curr_mask = cv2.inRange(gray, col_to_be_changed_low,col_to_be_changed_high)
gray[curr_mask > 0] = (high)
high -= 15
if(low == 0 ):
break
image = cv2.imread('ombre_circle.png')
viewImage(image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
grayscale_17_levels(gray)
viewImage(gray)
Whenever I run the code I get the error:
Kernel Restarting
The kernel for main.ipynb appears to have died. It will restart automatically.
I when I comment out these lines:
#cv2.namedWindow('Display', cv2.WINDOW_NORMAL)
#cv2.imshow('Display', image)
the core runs and prints out 'test' and I don't get an error.
I'm using:
Ubuntu-server 18.04
Jupyter lab 1.1.3
opencv-python 4.1.1.26
I run this on a server not on my local environment
I found a workaround for this issue by displaying it with Matplotlib:
def viewImage(image):
plt.subplot(122)
plt.title("RGB")
plt.imshow(image)
plt.show()
image = cv2.imread('img/ombre_circle.png')
viewImage(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
grayscale_17_levels(gray)
viewImage3(cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB))
However this doesn't solve the issue and takes extra transformations/code so I would like to find a solution to display with opencv.
X11 forwarding is enabled.
I tried opening an SSH connection with the -Y and -C flag (via this question) but this doesn't fix it.
Any ideas what could be the issue?
IPython Github Issue
What I understand from the discussion is that it's a C-level linking or runtime error from the openCV code being run.
I faced the same problem, got solved by using matplotlib SO jupyternb crash
image=cv2.imread("the file")
cv2.imshow("test file", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
I encountered similar issue when I'm loading large tiff files. Same code works for small tiff files. You can look at this post to compress your image then display.
cv2.imshow() would cause Jupyter sessions
to crash: this post of the issue.
As a substitution, please consider using
from google.colab.patches import cv2_imshow on Google Colab.

Alternative to .dilate() OpenCV

I am using cv2 and Pillow in my script:
image = Image.open("img1.png")
#do some stuff to the image
image.save("result1.png")
image = cv2.imread("result1.png")
kernel = np.ones((5, 5), np.uint8)
dilated_image = cv2.dilate(image, kernel, iterations=3)
cv2.imwrite("result2.png", dilated_image)
final_image = Image.open("result2.png")
#do some other stuff to the image
final_image.save("final_result.png")
As you can see, I have to switch between OpenCV and Pillow, and save three images. What I want, is to save just one result, instead of three.
Is there a way, where I can continue with Pillow, dilate the image with almost the same execution speed, without using cv2?
I have already tried image.filter(ImageFilter.MaxFilter(size=3)), but it takes too much CPU time. The reason it takes too much time, is that for having the same effect as cv2.dilate(image, kernel, iterations=5), I should use at least image.filter(ImageFilter.MaxFilter(size=15))
If you are just looking for an OpenCV alternative for the function which is there in a standard library, then you can try SciPy's function (SO Question here)

cv2.FeatureDetector_create('SIFT') causes segmentation fault

I am using opencv 2.4.11 and python 2.7 for a computer vision project.
I am trying to obtain the SIFT descriptors:
ima = cv2.imread('image.jpg')
gray = cv2.cvtColor(ima,cv2.COLOR_BGR2GRAY)
detector = cv2.FeatureDetector_create('SIFT') # or 'SURF' for that matter
descriptor = cv2.DescriptorExtractor_create('SIFT')
kpts = detector.detect(gray)
When calling the last instruction it throws an ugly segmentation fault. I have to use a 2.4.x version, so uploading to the 3.x version of opencv to use SIFT or SURF methods is not an option. I have downgraded from 3.1 previously using sudo make uninstall and installed from 0 the actual opencv version.
Does anyone have an idea why this happens?
Try:
import cv2
ima = cv2.imread('image.jpg')
gray = cv2.cvtColor(ima, cv2.COLOR_BGR2GRAY)
detector = cv2.SIFT()
kp1, des1 = detector.detectAndCompute(gray, None)
detector = cv2.FeatureDetector_create('SIFT') should also work for creating the SIFT object.
currently I am beginner in Computer Science so apologize for my short explanation.
I have OpenCV 3 and Python 2.7.11
Before all I downloaded no no it's better that you read this site
after all you can write this code (It's almost the same of your code ).
import cv2
import numpy as np
img = cv2.imread('lenna.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
detector = sift.detect(gray, None)
kpts, des = sift.compute(gray, detector)
# kpts,des=descriptor.compute(gray,kpts)
im_with_keypoints = cv2.drawKeypoints(gray, kpts, np.array([]), color=255, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
cv2.imshow("Keypoints", im_with_keypoints)
cv2.waitKey()
Regards!
Install opencv_contrib using
pip install opencv-contrib-python
Then your code will work.

Why does Python cv2 modules depend on (old) cv

I'm new to OpenCV and would like to use its Python binding.
When trying out the samples on OSX, I noticed
1.) The windows imshow creates are not resizable
2.) I can fix that with an prior call to cv2.namedWindow, like:
cv2.namedWindow('zoom', cv2.cv.CV_WINDOW_NORMAL)
Can we add symbols like CV_WINDOW_NORMAL from cv into cv2 !?
Who has commit rights to openCV's Python binding ?
Thanks,
Sebastian Haase
There are some omisions in the current new cv2 lib. Typically these are constants that did not get migrated to cv2 yet and are still in cv only.
Here is some code to help you find them:
import cv2
import cv2.cv as cv
nms = [(n.lower(), n) for n in dir(cv)] # list of everything in the cv module
nms2 = [(n.lower(), n) for n in dir(cv2)] # list of everything in the cv2 module
search = 'window'
print "in cv2\n ",[m[1] for m in nms2 if m[0].find(search.lower())>-1]
print "in cv\n ",[m[1] for m in nms if m[0].find(search.lower())>-1]
cv2 is a more faithful wrapper around the C++ libs than the previous cv. I found it confusing at first but it is much easier once you make the change. The code is much easier to read and numpy matrix manipulations are very fast.
I suggest you find and use the cv constants while reporting their omissions as bugs to the opencv bug tracker at willowgarage. cv2 is fresh and minty but will improve.
FYI. it is well worth instantiating the named windows before use, also killing them on exit. IMHO
E.g.
import cv2
if __name__ == '__main__':
cap = cv2.VideoCapture(0) # webcam 0
cv2.namedWindow("input")
cv2.namedWindow("grey")
key = -1
while(key < 0):
success, img = cap.read()
cv2.imshow("input", img)
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("grey", grey)
key = cv2.waitKey(1)
cv2.destroyAllWindows()

Categories

Resources