Edge detection and histogram matching of two images using open CV python. - python

I need to find edge detection of medical images using OpenCV python .Which edge detector will be the best suited for my work? I have tried using canny Edge detector. I want to find edges of the medical images and find the histogram matching between two images.
Thanks in Advance:)

Can you post the images you're working on ? That will be better.
Also, you can try this code. It allows you to change the parameters of canny filters, Thresold 1 and thresold 2 and hence you will get an overall idea how you can apply canny filter to the image.
import cv2
import numpy as np
def nothing(x):
pass
#image window
cv2.namedWindow('image')
#loading images
img = cv2.imread('leo-messi-pic.jpg',0) # load your image with proper path
# create trackbars for color change
cv2.createTrackbar('th1','image',0,255,nothing)
cv2.createTrackbar('th2','image',0,255,nothing)
while(1):
# get current positions of four trackbars
th1 = cv2.getTrackbarPos('th1','image')
th2 = cv2.getTrackbarPos('th2','image')
#apply canny
edges = cv2.Canny(img,th1,th2)
#show the image
cv2.imshow('image',edges)
#press ESC to stop
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
As far as, histogram comparison is concerned. You can find all the histogram related cv2 APIs here.
http://docs.opencv.org/modules/imgproc/doc/histograms.html
Hope it helps.

Related

Roi custom OpenCV

I have a video stream where I do the detection of people using Opencv and python.
My ROI is rectangular, but I would like to make a custom shape as in the figure.
It seems this is a stationary camera. If so, you can hard code the rectangular region of interest. You can then use a mask (created with for instance MS Paint) to black out everything outside of the custom shape.
Result:
Code:
import cv2
# load image
img = cv2.imread('image.jpg')
# load mask
mask = cv2.imread('roi_mask.png',0)
# create subimage
roi = img[120:350,150:580]
# mask roi
masked_roi = cv2.bitwise_and(roi,roi,mask=mask)
# display result
cv2.imshow('Roi',roi)
cv2.imshow('Mask',mask)
cv2.imshow('Result',masked_roi)
cv2.waitKey(0)
cv2.destroyAllWindows()

Finding bright spots in a image using opencv

I want to find the bright spots in the above image and tag them using some symbol. For this i have tried using the Hough Circle Transform algorithm that OpenCV already provides. But it is giving some kind of assertion error when i run the code. I also tried the Canny edge detection algorithm which is also provided in OpenCV but it is also giving some kind of assertion error. I would like to know if there is some method to get this done or if i can prevent those error messages.
I am new to OpenCV and any help would be really appreciated.
P.S. - I can also use Scikit-image if necessary. So if this can be done using Scikit-image then please tell me how.
Below is my preprocessing code:
import cv2
import numpy as np
image = cv2.imread("image1.png")
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
binary_image = np.where(gray_image > np.mean(gray_image),1.0,0.0)
binary_image = cv2.Laplacian(binary_image, cv2.CV_8UC1)
If you are just going to work with simple images like your example where you have black background, you can use same basic preprocessing/thresholding then find connected components. Use this example code to draw a circle inside all circles in the image.
import cv2
import numpy as np
image = cv2.imread("image1.png")
# constants
BINARY_THRESHOLD = 20
CONNECTIVITY = 4
DRAW_CIRCLE_RADIUS = 4
# convert to gray
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# extract edges
binary_image = cv2.Laplacian(gray_image, cv2.CV_8UC1)
# fill in the holes between edges with dilation
dilated_image = cv2.dilate(binary_image, np.ones((5, 5)))
# threshold the black/ non-black areas
_, thresh = cv2.threshold(dilated_image, BINARY_THRESHOLD, 255, cv2.THRESH_BINARY)
# find connected components
components = cv2.connectedComponentsWithStats(thresh, CONNECTIVITY, cv2.CV_32S)
# draw circles around center of components
#see connectedComponentsWithStats function for attributes of components variable
centers = components[3]
for center in centers:
cv2.circle(thresh, (int(center[0]), int(center[1])), DRAW_CIRCLE_RADIUS, (255), thickness=-1)
cv2.imwrite("res.png", thresh)
cv2.imshow("result", thresh)
cv2.waitKey(0)
Here is resulting image:
Edit: connectedComponentsWithStats takes a binary image as input, and returns connected pixel groups in that image. If you would like to implement that function yourself, naive way would be:
1- Scan image pixels from top left to bottom right until you encounter a non-zero pixel that does not have a label (id).
2- When you encounter a non-zero pixel, search all its neighbours recursively( If you use 4 connectivity you check UP-LEFT-DOWN-RIGHT, with 8 connectivity you also check diagonals) until you finish that region. Assign each pixel a label. Increase your label counter.
3- Continue scanning from where you left.

To remove the grids in an image using python opencv

I am new to field of image processing in python opencv.
I want to remove the grid lines in the given image and show the output as a plain dark green image
I applied canny edge detection to detect the edges and then subtracting the image from edges . But its not showing the result as expected. Please suggest what can be done
Code
import numpy as np
import cv2
image = cv2.imread('Input image')
cv2.imshow("Original",image)
edges = cv2.Canny(image,100,200)
cv2.imshow("Canny",edges)
gray_image_RGB = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
print gray_image_RGB.shape[:]
cv2.imshow("Converted",gray_image_RGB)
outputimage=image-gray_image_RGB
cv2.imshow("Output",outputimage)
cv2.waitKey(0)
cv2.destroyAllWindows()

Python: How to keep region inside canny close edge's area

I'm using canny algorithm to find the edges.
Next, I want to keep the region inside the closed curves.
My code sample is:
import cv2
import numpy as np
from matplotlib import pyplot as plt
import scipy.ndimage as nd
from skimage.morphology import watershed
from skimage.filters import sobel
img1 = cv2.imread('coins.jpg')
img = cv2.imread('coins.jpg',0)
edges= cv2.Canny(img,120,200)
markers = np.zeros_like(img)
markers[edges<50] = 0
markers[edges==255] = 1
img1[markers == 1] = [0,0,255]
img1[markers == 0] = [255,255,255]
cv2.imshow('Original', img)
cv2.imshow('Canny', img1)
#Wait for user to press a key
cv2.waitKey(0)
My output image is
I want to show the original pixels values inside the coins. Is that possible?
I suggest you use an union-find structure to get the connected components of white pixels of your img1. (You might want to find the details of this algorithm on Wikipedia : https://en.wikipedia.org/wiki/Disjoint-set_data_structure).
Once you have the connected components, my best idea is to consider the conected components that do not contain any point on the border of your picture (they should correspond to the interior of your coins) and color them in the color of img.
Sure, you may have some kind of triangles between your coins that will still be colored, but you could remove the corresponding connected components by hand.
Not really. The coin outlines are not continuous so that any kind of filling will leak.
You can repair the edges by some form of morphological processing (erosion), but this will bring the coins in contact and create unreachable regions between them.
As a fallback solution, you can try a Hough circle detector and mask inside the disks.

Pattern recognition in OpenCV using Python

Currently I am trying to create a pattern recognition program as a pet project. It involves jpeg files of knitting swatches and basically recognizing the stitches out of the swatch. Each stitch essentially takes the shape of an inverted 'v'.
So far have managed to get current versions of OpenCV in Python up and running in a Visual Studio environment using the inbuilt Canny Edge detection but am unsure how to progress from there because am reading up on edge detection methods and finding there are quite many.
If anyone can point me in the right way would appreciate it a lot.
So heres the code:
import numpy as np
import cv2
#Defining the autocanny function
def auto_canny(image, sigma=0.10):
#compute median of image thresholds
v = np.median(image)
#apply automatic canny edge detection using the computed median
lower = int(max(0,(1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
edged = cv2.Canny(image, lower, upper)
#return the edged image
return edged
#defining the image, grayscale, blurred
image = cv2.imread('img_knit_sample2.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
#apply Canny edge detection using a wide threshold, tight
#threshold, and automatically determined threshold
wide = cv2.Canny(blurred, 10, 200)
tight = cv2.Canny(blurred, 225, 250)
auto = auto_canny(blurred)
#show the images
cv2.imshow("Original", image)
cv2.imshow("Edges-wide", wide)
cv2.imshow("Edges-tight", tight)
cv2.imshow("Edges-auto", auto)
#Save the images to disk
cv2.imwrite('Wide_config.jpg', wide)
cv2.imwrite('Tight_config.jpg', tight)
cv2.imwrite('Autocanny.jpg', auto)
cv2.waitKey(0)
cv2.destroyAllWindows()
Unfortunately i cannot upload more than 2 images but am more than happy to get the URL's for anyone willing to go further
(Apologies for the crappy description since I am new to this and if you do understand my query and can still help then kudos and much appreciation to you)
Cheers
Edges appear where there is contrast, i.e. at the limit between zones of a different color (intensity). In your picture, this is essentially between the blue and black wools.
You can see some separation between the blue threads, but these are ridges, not edges, and you'd better use a ridge detector.
In the black areas, seeing the edges is hopeless. Don't even try.
If your goal is to locate the stitches, you may be more lucky with template matching.

Categories