Blur the edges of image in Python - python

I'm trying to read a binary RGB image and blur just the edges. This is my non-working code upto now. I get this error: "ValueError: operands could not be broadcast together with shapes (2048,2048,3) (2048,2048)"
import cv2
import numpy as np
import skimage.exposure
import matplotlib.pyplot as plt
# load image
img = cv2.imread('mask.png')
# Get edges
edges = cv2.Canny(image=img.astype(np.uint8), threshold1=100, threshold2=200) # Canny Edge Detection
#Remove edges from image
img = img - edges
# Blur
blur = cv2.GaussianBlur(edges, (0,0), sigmaX=2.5, sigmaY=2.5, borderType = cv2.BORDER_DEFAULT)
img = img + blur
# save output
cv2.imwrite('bw_image_antialiased.png', img)
Is there a better way to do this? Faster, more efficient?

Related

How to Enhance Image contrast and brightness

I have a input image and i want to improve contrast and brightness
input image:
After run my code result is:
But finally image i want(Clarity filter in Windows 10 Photos app in edit mode you can use this link for more details https://www.digitalunite.com/technology-guides/digital-photography/editing-photos-and-videos-windows-10-using-photos-app):
(more details and better separation of objects and color)
My code is:
import cv2
import numpy as np
import skimage.filters as filters
from PIL import ImageFilter,ImageEnhance
# read the image
img = cv2.imread('input.png')
# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# blur
smooth = cv2.GaussianBlur(gray, (95,95),0)
# divide gray by morphology image
division = cv2.divide(gray, smooth, scale=40)
# sharpen using unsharp masking
result = filters.unsharp_mask(division, radius=2.5, amount=1, multichannel=False, preserve_range=False)
result = (220*result).clip(0,220).astype(np.uint8)
cv2.imshow('smooth', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Generation of skeleton from fiber image

I am new to image processing. I am doing image processing of fiber image to generate skeleton using morphology function from skimage. The generated skeleton shows lots of small unnecessary loops/circles around it. I need a single medial axis line (skeleton) for each fiber in image. I have used following code to generate skeleton. Also, attached original and skeleton image for reference. Can someone help in to improve the skeleton generation step?
[import cv2
import numpy as np
from skimage import morphology
img = cv2.imread('img.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# dilate and threshold
kernel = np.ones((2, 2), np.uint8)
dilated = cv2.dilate(gray, kernel, iterations=1)
ret, thresh = cv2.threshold(dilated, 215, 255, cv2.THRESH_BINARY_INV)
cv2.imwrite('Binary.jpg',thresh)
# skeletonize
skeleton = morphology.skeletonize(thresh, method='lee')
skeleton = morphology.remove_small_objects(skeleton.astype(bool), 100, connectivity=2)
cv2.imwrite('Skeleton.jpg',skeleton*255)]
I'm not seeing the skeleton. Here's what I was able to come up with binary thresholding + morphological operations + small object clean up:
from skimage.morphology import binary_opening, binary_closing, thin, disk, remove_small_objects, remove_small_holes
from skimage.filters import threshold_otsu
from skimage.color import rgb2gray
import numpy as np
img_gray = rgb2gray(img) # image was rgb for me
mask = img_gray < threshold_otsu(img_gray) + 15/255
mask = binary_opening(binary_closing(mask, disk(2)), disk(2))
mask = remove_small_objects(mask, 300)
mask = remove_small_holes(mask, 300)
skeleton = thin(mask)
plot(skeleton)
You can probably play around with the kernel shape for the opening/closing, as well as use individual erosion/dilation operations, to get a stronger output. You may also try different skeletonizing techniques, as I know different ones produce varying results.

OpenCV Contour Detection in color

I'm trying to detect the optic disc in an image of the back of the eye using OpenCV and findContour, then fitEllipse, but my program isn't detecting the optic disc at all. How do I fix this? Code and images are below
import cv2
import numpy as np
from sklearn.linear_model import LinearRegression
import math
from decimal import Decimal
def find_elongation(image):
img = cv2.imread(image,0)
ret,thresh = cv2.threshold(img,127,255,0)
contour,hierarchy = cv2.findContours(thresh, 1, 2)
contours = []
for i in range(len(contour)):
if len(contour[i])>=5:
contours.append(contour[i])
cnt = contours[0]
k = cv2.isContourConvex(cnt)
ellipse = cv2.fitEllipse(cnt)
im = cv2.ellipse(img,ellipse,(0,255,0),2)
(x,y),(ma,Ma),angle = cv2.fitEllipse(cnt)
return Ma/ma
print(find_elongation('eye.png'))
print(find_elongation('eye2.png'))
print(find_elongation('eye3.png'))
Image (one of them):
I'm trying to get the brightly colored circle in the middle:
Thanks for the help!
I have developed a piece of code to implement what you have asked. It mainly uses de Value channel of the HSV color space followed by some morphological operations.
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Read the image
img = cv2.imread('so.png')
# Transform the image to HSV color-space and keep only the value channel
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)
# Threshold the iamge with the 95% of the brightest possible pixels
maxVal = np.max(v)
per = 0.95
_, th = cv2.threshold(v, maxVal*per, 255, cv2.THRESH_BINARY)
# Erode the image and find the connected components
th = cv2.erode(th, np.ones((2,2), np.uint8))
n, conComp, stats, centroids = cv2.connectedComponentsWithStats(th)
# Obtain the sizes of the connectedComponents skipping the background
sizes = stats[1:,-1]
# Obtain the number of the connectedComponent with biggest size
nComp = np.argmax(sizes) + 1
# Isolate the connectedComponent and apply closing
out = np.zeros((img.shape[0], img.shape[1]), np.uint8)
out[conComp==nComp] = 1
out = cv2.morphologyEx(out, cv2.MORPH_CLOSE, np.ones((10,10)))
# Apply gradient to mask to obtain the border of the ellipse
out = cv2.morphologyEx(out, cv2.MORPH_GRADIENT, np.ones((2,2)))
# Join the border of the ellipse with the image to display it
img[out==1] = (0,0,0)
plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
plt.show()
I attach the output I have obtained with the picture you posted:

Detection and segmentation of region of interest from X-ray images

I am working on some Xray images and I want to detect and segment region of interest from the image.
Consider input image
I want to detect square like shapes in the image, as highlighted in the image
Output: region of interest will somehow look like this
This is my code which I have done so far
import cv2
import numpy as np
import pandas as pd
import os
from PIL import Image
import matplotlib.pyplot as plt
from skimage.io import imread, imshow
img = cv2.imread('image.jpg',0)
imshow(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
imshow(gray)
equ = cv2.equalizeHist(img)
imshow(equ)
img_resize = cv2.resize(img, (300, 300))
print(img_resize.shape)
figure_size = 9
new_image_gauss = cv2.GaussianBlur(img_resize, (figure_size, figure_size),0)
imshow(new_image_gauss)
img_edge = cv2.Canny(equ,100,200)
# show the image edges on the newly created image window
imshow(img_edge)
kernel = np.ones((5,5), np.uint8)
img_erosion = cv2.erode(img_edge, kernel, iterations=1)
img_dilation = cv2.dilate(img_edge, kernel, iterations=1)
imshow(img_erosion)
Results which I have got;
Please guide me.
TIA
One thing that might help is to do morphology gradient on your image to emphasize the edges in Python OpenCV before you do your Canny edge detection.
Input:
import cv2
import numpy as np
# read image
img = cv2.imread("xray2.jpg")
# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# do morphology gradient
kernel = cv2.getStructuringElement(cv2.MORPH_RECT , (3,3))
morph = cv2.morphologyEx(gray, cv2.MORPH_GRADIENT, kernel)
# apply gain
morph = cv2.multiply(morph, 5)
# write results
cv2.imwrite("xray2_gradient_edges.jpg",morph)
# show lines
cv2.imshow("morph", morph)
cv2.waitKey(0)

Detect a scratch on noise image with OpenCV

I am trying to get a small scratch from the noise image as shown. It is quite noticeable by eyes, but I would like to identify it using OpenCV Python.
I tried to use image blurring and subtract it from the original image, and then threshold to get a image as the second.
Could any body please advise to get this scratch?
Original image:
Image after blurring, subtraction, and threshold:
This is how I process this image:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("scratch0.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.blur(gray,(71,71))
diff = cv2.subtract(blur, gray)
ret, th = cv2.threshold(diff, 13, 255, cv2.THRESH_BINARY_INV)
cv2.imshow("threshold", th)
cv2.waitKey(0)

Categories