edge detection using python - python

import cv2
import numpy as np
cap = cv2.VideoCapture()
while True:
_, frame = cap.read()
laplacia = cv2.Laplacian(frame, cv2.CV_64F)
cv2.imshow('original', frame)
cv2.imshow('laplacian', laplacia)
k = cv2.waitKey(5) & 0xFF
if k==27:
break
cv2.destroyAllWindows()
cap.release()
I am getting this error
#laplacia = cv2.Laplacian(frame, cv2.CV_64F)
cv2.error: C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\core\src\matrix.cpp:981: error: (-215) dims <= 2 && step[0] > 0 in function cv::Mat::locateROI

cv2.Laplacian() won't work with Color images.
You can go through OpenCV Documentation for knowing more..Image Gradients
You must convert the frame you have captured to gray scale and then apply Laplacian
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
You can convert to gray scale as shown above..

Related

How to remove noise from CLAHE, Python?

I was trying to figure out a way to read the veins in an video capture (i am using special camera) using OpenCV in Python, but there are too many noise from the results i got. Can someone help?
here is the result: https://ibb.co/cbdxY5F
i want all in the red circle to be clear without nosie: https://ibb.co/C9SPjyX
import cv2
import numpy as np
import time
def multi_clahe(img, num):
for i in range(num):
img = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(4+i*2,4+i*2)).apply(img)
return img
img = cv2.VideoCapture(1)
while(True):
ret, frame = img.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cl3 = multi_clahe(cl1, 5)
cv2.imshow('image', cl3)
k = cv2.waitKey(1) & 0xFF
if k == ord("a")
cv2.imwrite(time.strftime("Screenshot%Y%m%d%H%M%S.jpg"),final)
cv2.imwrite(time.strftime("1.jpg"),cl3)
cv2.imwrite("temp.jpg",cl3)
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
img.release()
cv2.destroyAllWindows()
I need to remove noises from CLAHE in Python.

img data type = 17 is not supported

Ive got a video which ive im trying to show a specific region using cv2.polyfill and bitwise operation. When I do this on a image it works fine but when done on a video it comes up with the following error. Ive had no problems doing this earlier on with another picture/video. The region to be shown does show up as a frozen picture but also crashes the kernel. The code is:
import cv2
import numpy as np
cap = cv2.VideoCapture("heartvideo.wmv",0)
def roi(frame):
mask = np.zeros_like (frame)
array = np.array([[148,550],[300,650],[400,680],[800,680],[880,560],[555,70],[492,50]])
contours = np.array([[50,50], [50,150], [150,150], [150,50]])
cv2.fillPoly(mask, pts = [array], color =(255))
masked = cv2.bitwise_and(mask,frame)
return mask
while(cap.isOpened()): # while video is initialised
ret, frame = cap.read() #reads the video bit by bit
adj = roi(frame)
if ret:
cv2.imshow("Image", adj)
else:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
if cv2.waitKey(15) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'fillPoly'
Overload resolution failed:
img data type = 17 is not supported
Expected Ptr<cv::UMat> for argument 'img'
The issue is that you're using a 3-channel BGR mask (datatype 17 is a 3-channel image). You used np.zeros_like(frame) to set your mask which means that it'll have the exact same dimensions as the image you passed in. If you meant for it to be a 1-channel image you should set the dimensions.
I'm not sure what version of OpenCV you're using and I can't replicate the error with OpenCV 4.4. On this version it allows a 3-channel image even if you've specified a 1-channel color as the fillPoly argument though it does this by assuming you meant (255,0,0) for the color. It could be that on a different version of OpenCV the color dimensions had to match the image dimensions and it's complaining about that.
Try out this revised version of the code and see if it works.
import cv2
import numpy as np
def roi(frame):
# draw a polygon on mask
height,width = frame.shape[:2];
mask = np.zeros((height, width), np.uint8);
array = np.array([[148,550],[300,650],[400,680],[800,680],[880,560],[555,70],[492,50]])
contours = np.array([[50,50], [50,150], [150,150], [150,50]])
cv2.fillPoly(mask, pts = [array], color =(255))
# mask stuff on frame
# masked = cv2.bitwise_and(mask,frame)
copy = np.zeros_like(frame);
copy[mask == 255] = frame[mask == 255];
return copy;
# open video
cap = cv2.VideoCapture("heartvideo.wmv", 0);
while(cap.isOpened()): # while video is initialised
ret, frame = cap.read() #reads the video bit by bit
if ret:
adj = roi(frame)
cv2.imshow("Image", adj)
else:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
if cv2.waitKey(15) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

Controlling Contrast and Brightness of Video Stream in OpenCV and Python

I’m using OpenCV3 and Python 3.7 to capture a live video stream from my webcam and I want to control the brightness and contrast. I cannot control the camera settings using OpenCV's cap.set(cv2.CAP_PROP_BRIGHTNESS, float) and cap.set(cv2.CAP_PROP_BRIGHTNESS, int) commands so I want to apply the contrast and brightness after each frame is read. The Numpy array of each captured image is (480, 640, 3). The following code properly displays the video stream without any attempt to change the brightness or contrast.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
I get a washed-out video stream when I use Numpy’s clip() method to control the contrast and brightness, even when I set contrast = 1.0 (no change to contrast) and brightness = 0 (no change to brightness). Here is my attempt to control contrast and brightness.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
contrast = 1.0
brightness = 0
frame = np.clip(contrast * frame + brightness, 0, 255)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
How can I control the contrast and brightness of a video stream using OpenCV?
I found the solution using the numpy.clip() method and #fmw42 provided a solution using the cv2.normalize() method. I like the cv2.normalize() solution slightly better because it normalizes the pixel values to 0-255 rather than clip them at 0 or 255. Both solutions are provided here.
The cv2.normalize() solution:
Brightness - shift the alpha and beta values the same amount. Alpha
can be negative and beta can be higher than 255. (If alpha >= 255,
then the picture is white and if beta <= 0, then the picure is black.
Contrast - Widen or shorten the gap between alpha and beta.
Here is the code:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cv2.normalize(frame, frame, 0, 255, cv2.NORM_MINMAX)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
The numpy.clip() solution:
This helped me solve the problem: How to fast change image brightness with python + OpenCV?. I need to:
Convert Red-Green Blue (RGB) to Hue-Saturation-Value (HSV) first
(“Value” is the same as “Brightness”)
“Slice” the Numpy array to the Value portion of the Numpy array and adjust brightness and contrast on that slice
Convert back from HSV to RGB.
Here is the working solution. Vary the contrast and brightness values. numpy.clip() ensures that all the pixel values remain between 0 and 255 in each on the channels (R, G, and B).
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
contrast = 1.25
brightness = 50
frame[:,:,2] = np.clip(contrast * frame[:,:,2] + brightness, 0, 255)
frame = cv2.cvtColor(frame, cv2.COLOR_HSV2BGR)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
import cv2 as cv
cap = cv.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = cap.read()
# normalize the frame
frame = cv.normalize(
frame, None, alpha=0, beta=255, norm_type=cv.NORM_MINMAX, dtype=cv.CV_8UC1
)
# Display the resulting frame
cv.imshow("frame", frame)
# press q to quit
if cv.waitKey(1) & 0xFF == ord("q"):
break

Laplacian and Sobel Functions in open cv are not working properly

I am trying to run the Laplacian and Sobel Function to test the edge and gradients of the video streaming but while running the mentioned below code
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(1):
# Take each frame
_, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_red = np.array([30,150,50])
upper_red = np.array([255,255,180])
mask = cv2.inRange(hsv, lower_red, upper_red)
res = cv2.bitwise_and(frame,frame, mask= mask)
laplacian = cv2.Laplacian(frame,cv2.CV_64F)
sobelx = cv2.Sobel(frame,cv2.CV_64F,1,0,ksize=5)
sobely = cv2.Sobel(frame,cv2.CV_64F,0,1,ksize=5)
cv2.imshow('Original',frame)
cv2.imshow('Mask',mask)
cv2.imshow('laplacian',laplacian)
cv2.imshow('sobelx',sobelx)
cv2.imshow('sobely',sobely)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
cap.release()
I am facing the error using this problem, I though search from google also and trying to degrade the version of OpenCV 4 to OpenCV 3 and which is also not working on the laptop and facing error
Traceback (most recent call last):
File "C:\Users\Misha\Desktop\test\CV\Edge Detection and Gradients.py", line 24, in <module>
cv2.imshow('laplacian',laplacian)
cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\highgui\src\window_w32.cpp:1230: error: (-215:Assertion failed) dst.data == (uchar*)dst_ptr in function 'cvShowImage'
Any kind of useful advice on this will be a great help.

python How can I fix OpenCV cvtColor error?

Here is the erroneous code:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)
while(True):
ret, frame = cap.read()
frame = cv2.flip(frame, -1)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', frame)
cv2.imshow('gray', gray)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
this is the error I'm getting:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: /home/piwheels/opencv-python/opencv/modules/imgproc/src/color.cpp:10638: error: (-215) scn == 3 || scn == 4 in function cvtColor
I'm not sure how to fix this. Can you help me?
What the error message say is that your input image to cvtColor (frame) should have either three (R, G, B) or four (R, G, B, A) channels to convert it to grayscale, and it does not.
This can happen because:
Your camera does not capture an image at all
It captures the image in grayscale
First, comment the lines
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
and
cv2.imshow('gray', gray)
and test if you can see the captured frames. Most likely you won't see color images, and that (image capture) could be where the problem is.

Categories

Resources