I am trying to run this program in jupyter notebook, but it's not running at all. It's just showing the asterisk beside the program. Can anyone tell me why is that happening? I have also tried other programs of OpenCV as well, but the result was the same. None of them are running.
import cv2
import numpy as np
image = cv2.imread('images/input.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow('Original image',image)
cv2.imshow('Gray image', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
Try this following code, opencv imshow cause issues with notebook.
from matplotlib import pyplot as plt
import cv2
image = cv2.imread('images/input.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
plt.imshow(gray)
plt.title('Gray image')
plt.show()
Related
I have a problem here during cropping and saving image by using opencv.
I'm trying to crop by using cv2.SelectROI function but after I drag on the image, cv.2imshow won't work properly.
Here's my code:
import cv2, numpy as np
img = cv2.imread('C:/git/ML/Image/colorful.jpg')
x,y,w,h = cv2.selectROI('img', img, False)
if w and h:
roi = img[y:y+h, x:x+w]
cv2.imshow('cropped', roi)
cv2.moveWindow('cropped', 0, 0)
cv2.imwrite('cropped2.jpg',roi)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(x,y,w,h)
I've tried to change directory in various ways, put imshow method just before selectROI but none of them worked so far.
cv2.imshow itself shouldn't be a problem because when I don't use selectROI and just manually code the cropping performance from start to finish(by defining mouseleftbutton click, drag, leftbuttonup one by one), cv2.imshow, cv2.movewindow and cv2.imwrite works just fine.
also, not confident that the code itself have interal problem because in other computer, those activities(dragging, cropping, open in new window, save) seems to be working just fine.
is there a possibility that i haven't installed sth that should be needed in order to run selectROI..?
Anyways.. any comments will be much appreciated. Plz help me.
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.
In this code we are preprocessing an RGB image for Tesseract OCR using tools such as cv2, NumPy and PIL. When this code is executed in the Python 2.7.13 Shell, I recieve the following error message.
Traceback (most recent call last): File "C:\Automation\OCR\images\OCR_Preprocessing_ RGB.py", line 23, in <module> cv2.THRESH_BINARY,11,2) error: C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\imgproc\src\thresh.cpp:1446: error: (-215) src.type() == CV_8UC1 in function cv::adaptiveThreshold
Here is the code that error generated from. I have marked lines of code where I think the problem may be.
import cv2
import numpy as np
from matplotlib import pyplot as plt
from cycler import cycler
from PIL import Image, ImageEnhance
# Loads the image then enhances it
image = Image.open('teleCapture.png')
contrast = ImageEnhance.Contrast(image)
img = contrast.enhance(2)
img = np.asarray(img)
r,g,b,a = cv2.split(img) // I know the issue is here, I have too many channels for an RGB image or I am merginf them wrong.
contrast = cv2.merge([b,g,r]) //"Contrast" was used as a src during Thresholding, is this what it should be?
# Adaptive Gaussian Thresholding //The problem may be within the thresholding, does this thresholding function only work using grayscale images?
th1 = cv2.adaptiveThreshold(contrast,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,11,2)
# Otsu's thresholding
ret2,th2 = cv2.threshold(contrast,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# Otsu's thresholding after Gaussian filtering
blur = cv2.GaussianBlur(contrast,(5,5),0)
ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# writes enhanced and thresholded img
cv2.imwrite('preprocessedTeleCapture.png', th2)
Threshold method need 1 channel image as input, and you give 3 channel, that's the problem shown in error message.
I check other question on google or stackoverflow, they are talking about run cv2.imshow in script, but my code run in jupyter notebook.
Here is my configuration:
ubuntu 16.4x64
python 3.5
opencv 3.1.0
I start a jupyter notebook: here is the code I put it notebook:
%pylab notebook
import cv2
cvim2disp = cv2.imread('data/home.jpg')
cv2.imshow('HelloWorld', cvim2disp)
cv2.waitKey() #image will not show until this is called
cv2.destroyWindow('HelloWorld') #make sure window closes cleanly
When I execute these code. image will show in a pop up window, but I can not close this window by clicking the x on the top right corner, and a moment later, system will prompt me that the window is not responding, it will give me 2 choices: "wait" , "fore quit". if I hit wait, then It will show the same prompt later, If I hit 'fore quit', then the jupyter notebook kernel die and I have to start over.
I google around, many solution suggest that I should add this code
cv2.startWindowThread()
before imshow, but situation get worse, the kernel hang forever!.
anybody have some idea what's going on.
Here is the pic of my error:
%matplotlib inline
#The line above is necesary to show Matplotlib's plots inside a Jupyter Notebook
import cv2
from matplotlib import pyplot as plt
#Import image
image = cv2.imread("input_path")
#Show the image with matplotlib
plt.imshow(image)
plt.show()
I was having a similar problem, and could not come to a good solution with cv2.imshow() in the Jupyter Notebook. I followed this stackoverflow answer, just using matplotlib to display the image.
import matplotlib.pyplot as plt
# load image using cv2....and do processing.
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
# as opencv loads in BGR format by default, we want to show it in RGB.
plt.show()
The API documentation for cv2.waitKey() notes the following:
This function is the only method in HighGUI that can fetch and handle events, so it needs to be called periodically for normal event processing unless HighGUI is used within an environment that takes care of event processing.
So perhaps calling the function in an endless loop would make the window responsive? I haven't tested this, but maybe you would like to try the following:
import cv2
cvim2disp = cv2.imread('data/home.jpg')
cv2.imshow('img', cvim2disp)
while(True):
k = cv2.waitKey(33)
if k == -1: # if no key was pressed, -1 is returned
continue
else:
break
cv2.destroyWindow('img')
This will help you understand what is happening:
import cv2
cvim2disp = cv2.imread('data/home.jpg')
cv2.imshow('HelloWorld', cvim2disp)
cv2.waitKey(0)
cv2.destroyWindow('HelloWorld')
waitKey(0) method is waiting for an input infinitely. When you see a frame of the corresponding image, do not try to close the image using close in top right corner.
Instead press some key. waitkey method will take that as an input and it will return back a value. Further you can also check which key was pressed to close the frame.
Additionally waitKey(33) will keep the frame active for 33 ms and then close it automatically.
destroyWindow() will destroy the current frame if there.
destroyAllWindows() will destroy all the frames currently present.
This will solve.
if your facing problem in google collab ,you can use this patch
from google.colab.patches import cv2_imshow
cv2_imshow(img)
%matplotlib inline
from matplotlib import pyplot as plt
img = cv2.imread(valid_img_paths[1])
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
The following code works fine in Jupyter to show one image
%matplotlib inline
import cv2
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(videoFName)
ret, image = cap.read()
image=cv2.resize(image,None,fx=0.25,fy=0.25,interpolation=cv2.INTER_AREA)
plt.imshow(image)
plt.show()
If you want to show the video instead of an image in a separate window, use the following code:
import cv2
cap = cv2.VideoCapture(videoFName)
while cap.isOpened():
ret, image = cap.read()
image=cv2.resize(image,None,fx=0.25,fy=0.25,interpolation=cv2.INTER_AREA)
cv2.imshow('image',image)
k = cv2.waitKey(30) & 0xff # press ESC to exit
if k == 27 or cv2.getWindowProperty('image', 0)<0:
break
cv2.destroyAllWindows()
cap.release()
Make sure the window name match, otherwise it will not work. In this case I use 'image' as window name.
The new window that opens up from Jupyter uses the same kernel as notebook. Just add this below to the code and it would work fine.
cv2.waitKey(0)
cv2.destroyAllWindows()
image = cv2.imread(file_path)
while True:
# Press 'q' for exit
exit_key = ord('q')
if cv2.waitKey(exit_key) & 255 == exit_key:
cv2.destroyAllWindows()
break
cv2.imshow('Image_title', image)
I have just developed a library that is exactly similar to cv2.imshow and it can be used in both Jupyter and colab. It can update the window. Therefore you can easily see the video inside it. It uses HTML canvas and is browser friendly :)
Installation:
pip install opencv_jupyter_ui
Usage:
This is the replacement of cv2.imshow for Jupiter. you need only to replace cv2.imshow with jcv2.imshow. It will work in Jupiter.
First:
please import the library
import opencv_jupyter_ui as jcv2
Then:
change cv2.imshow ->jcv2.imshow
More details exist on the Github Repository. Binder Demo gif
It also supports jcv2.waitKey(100) and jcv2.destroyAllWindows(). In case of the absence of Jupyter, it fallbacks to original cv2 functionality.
In order to change the default keys you can use jcv2.setKeys(['a','b','esc']). Please follow the document for more information
I am not sure if you can open a window from Jupyter Notebook.
cv2.imshow expects a waitKey which doesn't work in Jupyter.
Here is what I have done (using OpenCV 3.3):
from IPython.display import display, HTML
import cv2
import base64
def imshow(name, imageArray):
_, png = cv2.imencode('.png', imageArray)
encoded = base64.b64encode(png)
return HTML(data='''<img alt="{0}" src="data:image/png;base64, {1}"/>'''.format(name, encoded.decode('ascii')))
img = cv2.imread('./media/baboon.jpg',cv2.IMREAD_COLOR)
imshow('baboon', img)
If you don't need to use cv2, just:
from IPython.display import Image
Image('./media/baboon.jpg')
I installed openCV and numpy libraries in python 2.7.
I've tested them using commands import cv2 and import numpy and it compiled.
But when I use the cv2.imshow('frame', ----) function it displays a window but not displaying the image. And it's showing " frame is Not Responding".
So, I tried with matplotlib functions for displaying image and it worked.
I inserted cv2.imshow function in the 2nd case and it worked.
Versions [Python-2.7.10, OpenCV-2.4.11]
Below is the code,
Case 1: Not Working,displaying window but not image (showing FRAME IS NOT RESPONDING)
import cv2
import numpy
img = cv2.imread('a.jpg')
cv2.imshow('FRAME',img)
Case 2: Working
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
img = mpimg.imread('a.jpg')
img2 = cv2.imread('b.jpg')
cv2.imshow('FRAME',img2)
plt.imshow(img)
plt.show()
imshow should be followed by waitKey function which displays the image for specified milliseconds. Otherwise, it won’t display the image. For example, waitKey(0) will display the window infinitely until any keypress (it is suitable for image display). waitKey(25) will display a frame for 25 ms, after which display will be automatically closed. (If you put it in a loop to read videos, it will display the video frame-by-frame). Here's a working example:
import cv2
img = cv2.imread('a.jpg')
cv2.imshow('FRAME', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Try using imread like this
img = cv2.imread('a.jpg',0)#grayscale
img = cv2.imread('a.jpg',1)#rgb