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()
Related
I'm working in text extraction process inside the table.But while removing the table lines it affecting the text's pixel.is is possible to keep the text pixel which is overlays on the table line pixel.
original image as RGB
this image is the cropped from original image for reference
output region
Use eroded (or dilated black objects) second image as mask for first image.
import cv2
import numpy as np
#images need equal size
original=cv2.imread('RdfpD.png')
mask = cv2.imread('zxLX4.png', cv2.IMREAD_GRAYSCALE)
se=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,5))
ret,thresh = cv2.threshold(mask,60,255,cv2.THRESH_BINARY_INV)
dilate = cv2.dilate(thresh,se,iterations = 1)
dilate=cv2.bitwise_not(dilate)
dilate=cv2.cvtColor(dilate, cv2.COLOR_GRAY2BGR)
out=cv2.max(dilate, original)
cv2.imwrite('out_5.png', out)
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()
I'm trying to solve a homework problem where I need to get a mask from one image (DAPI) and then apply it to the second image (NPM1) of cells (they are the same cells in the exact same location)
I've been running in circles for about 4 hours trying to get the mask applied using a True/False approach but it doesn't seem to work. I've tried and failed with a bunch of other approaches but just pasting the one that I thought would most likely work (I'm super new to coding)
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from skimage.color import rgb2gray
import cv2
#Load the images
image = np.array(Image.open("NOTREATDAPI.jpg"))
image1 = np.array(Image.open("NOTREATNPM1.jpg"))
No_Treat_DAPI = rgb2gray(image)
No_Treat_NPM1 = rgb2gray(image1)
plt.imshow(image)
#Create a mask using the DAPI image
arr = np.array(No_Treat_DAPI)
DAPI_stain = arr[:,0] > 25
plt.imshow(arr)
The DAPI image:
The NPM1 image:
I'm trying to only get the regions on the original image that have an intensity of 25 or greater so that all of the black space in the isn't counted towards the mask as I'm trying to get a histogram of intensity of the cells in the NPM1 image.
I limited my solution to the use of OpenCV, numpy, and matplotlib.
The general approach is the following:
Load both images as grayscale images, see cv2.imread.
Create a binary mask from the DAPI image using binary thresholding at intensity value 25, see cv2.threshold.
Do some morphological opening to get rid of possible small artifacts, see cv2.morphologyEx and cv2.getStructuringElement.
Calculate the histogram of the NPM1 image, only incorporating the masked pixels, see cv2.calcHist.
Here's the complete code:
import cv2
import matplotlib.pyplot as plt
import numpy as np
# Load images as grayscale
dapi = cv2.imread('images/NOTREATDAPI.jpg', cv2.IMREAD_GRAYSCALE)
npm1 = cv2.imread('images/NOTREATNPM1.jpg', cv2.IMREAD_GRAYSCALE)
# Create a mask using the DAPI image and binary thresholding at 25
_, mask = cv2.threshold(dapi, 25, 255, cv2.THRESH_BINARY)
# Do some morphological opening to get rid of small artifacts
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15)))
# Calculate the histogram using the NPM1 image and the obtained binary mask
hist = cv2.calcHist([npm1], [0], mask, [256], [0, 256])
# Show bar plot of calculated histogram
plt.bar(np.arange(256), np.squeeze(hist))
plt.show()
# Show mask image
cv2.imshow('Mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
The mask then looks like this:
And, the histogram might look like this:
Hope that helps!
P.S. Next time, better use the opencv and python tags instead of only using the cv2 tag. You'll reach way more people.
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.
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.