program is about removing the gradient background color
Currently it takes about 20 second for single image of size 420X560 size
code is
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np
import os
import cv2
def backgroundRemovel(url):
img = cv2.imread(url)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.title('original Image')
plt.show()
color=img[0,0]
firstPixelRGB = sRGBColor(color[0], color[1], color[2], is_upscaled=True);
firstPixelLab = convert_color(firstPixelRGB, LabColor);
t=img.shape
x_dim=t[0]
y_dim=t[1]
for i in range(x_dim):
for j in range(y_dim):
rgbCurPixel=img[i,j]
curPixelRGB=sRGBColor(rgbCurPixel[0], rgbCurPixel[1], rgbCurPixel[2], is_upscaled=True);
curPixelLab=convert_color(curPixelRGB, LabColor);
delta_e = delta_e_cie2000(firstPixelLab, curPixelLab);
#print("difference is "+str(delta_e))
if delta_e<15:
img[i, j] = (0, 0, 0)
return img
fnmae="image.jpeg"
open_cv_image = backgroundRemovel(fname)
plt.imshow(open_cv_image)
plt.title('Background Removed Image')
plt.show()
Input Image:
Desired:
if there is any better way to remove gradient background of image please do share
Related
Using scikit library I was analysing the defects' area and mean diameter. Here is the code and the respective segmented regions.
import cv2
import numpy as np
from matplotlib import pyplot as plt
from skimage import measure, io, img_as_ubyte
from skimage.color import label2rgb, rgb2gray
img = cv2.imread("F:\py_image_pro\pore.jpg", 0)
scale = 0.086 #1 pixel in microns
from skimage.filters import threshold_otsu
threshold = threshold_otsu(img)
thresholded_img = img < threshold
#plt.imshow(thresholded_img, cmap='gray')
#plt.show()
from skimage.segmentation import clear_border
edge_touching_removed = clear_border(thresholded_img)
label_image = measure.label(edge_touching_removed, connectivity=img.ndim)
#plt.imshow(label_image)
#plt.show()
image_label_overlay = label2rgb(label_image, image=img)
plt.imshow(image_label_overlay)
plt.show()
props = measure.regionprops_table(label_image, img, properties=['label', 'area', 'equivalent_diameter', 'mean_intensity', 'solidity'])
import pandas as pd
df = pd.DataFrame(props)
df = df[df['area'] > 20]
df['area_in_microns'] = df['area'] * (scale**2)
df['equivalent_diameter_microns'] = df['equivalent_diameter'] * (scale)
print(df.head())
Used regionprops to measure the segmented regions. Segmented image
I would like to know if there is any way to display the labels in the output image so that segmented labels' corresponding measurements can be known?
Are you asking whether you can display a colormapped version of the measurements on top of the image? If so, the answer is yes! You can use skimage.util.map_array for this.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from skimage import (
color, data, filters, measure,
morphology, segmentation, util
)
# grab the image
coins = data.coins()
# segment the image; from:
# https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_expand_labels.html
edges = filters.farid(coins)
markers = np.zeros_like(coins)
markers[coins < 30] = 1
markers[coins > 150] = 2
watershed = segmentation.watershed(edges, markers)
segmented_raw = measure.label(watershed == 2)
# remove tiny background objects due to noise
segmented = morphology.remove_small_objects(segmented_raw, 64)
# measure regionprops
table = pd.DataFrame(measure.regionprops_table(
segmented, coins, properties=('label', 'area')
))
# map the labels to measured properties
colored_by_area = util.map_array(
segmented,
np.asarray(table['label']),
np.asarray(table['area']).astype(float),
)
# set 0 to nan, so it appears as transparent in pyplot.imshow
colored_by_area[colored_by_area==0] = np.nan
# display the results
fig, axes = plt.subplots(1, 2, sharex=True, sharey=True)
colored_by_label = color.label2rgb(segmented, image=coins, bg_label=0)
axes[0].imshow(colored_by_label)
axes[0].set_axis_off()
axes[0].set_title('segmentation')
axes[1].imshow(coins, cmap='gray')
axim = axes[1].imshow(colored_by_area, cmap='viridis')
axes[1].set_axis_off()
axes[1].set_title('segment area')
plt.colorbar(axim, ax=axes[1], fraction=0.05, label='area (px)')
plt.show()
I'm trying to run a simple code that takes a traffic lights image & displays it as grayscale --> 'Original' and then takes the same image and displays only the parts of it which correspond to the upper and lower thresholds I pre-defined --> 'bright'. However, the following code when I run it, displays nothing.
when I change plt.imshow() to cv2.imshow() it does, so I'm confused as to why this happens. Both libraries are installed correctly. I even tried adding plt.show() at the end of the code, but still no output.
import cv2
import matplotlib.pyplot as plt
original = cv2.imread('traffic_lights.jpeg')
plt.imshow(original,cmap='gray')
lower=150
upper = 254
bright = cv2.inRange(original,lower,upper)
plt.imshow(bright,cmap='gray')
I think you need to specify a figure and axes, then plot the image on the axes.
import cv2
import matplotlib.pyplot as plt
original = cv2.imread('traffic_lights.jpeg')
plt.imshow(original,cmap='gray')
lower = 150
upper = 254
bright = cv2.inRange(original,lower,upper)
fig, ax = plt.subplots()
im = ax.imshow(bright,cmap='gray')
plt.show()
It helps to first convert your image as opencv image into the right color scale with cv2.COLOR_xxx:
import cv2
import matplotlib.pyplot as plt
original = cv2.imread('traffic_light.jpg')
original = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
lower, upper = 150, 254
bright = cv2.inRange(image, lower, upper)
plt.imshow(bright,cmap='gray')
OpenCV imread functions reads the image in a B, G, R fashion.
Therefore if you read the image with imread and want to display with pyplot, first you need to convert the image into the R, G, B then display.
For instance:
import cv2
import matplotlib.pyplot as plt
if __name__ == '__main__':
img = cv2.imread("lights.jpg")
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.show()
Result:
If you don't convert using cvtColor the result will be:
The above for the RGB images, for gray images the correct answer will be:
import cv2
import matplotlib.pyplot as plt
if __name__ == '__main__':
img = cv2.imread("lights.jpg")
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(img_rgb, cmap='gray')
plt.show()
lower = 150
upper = 254
bright = cv2.inRange(img_rgb, lower, upper)
plt.imshow(bright, cmap='gray')
plt.show()
Result:
I need to make the pixels with the same intensity value in a list so I will get a list of lists of intensity values and each list has the pixels with the same intensity value.
import nibabel as nib
import numpy as np
from PIL import Image
import seaborn as sns
import matplotlib.pyplot as plt
from numpy import asarray
from scipy import ndimage, misc, stats
import cv2
### Load the image
img = nib.load('input_dir/FLAIR1.nii.gz')
img_data = img.get_fdata()
imgs = img_data[:, :, 23]
rows, col = imgs.shape
my_nlist = [[] for k in range(y.shape[0])]
print(im_arr[2,2])
for i in range(0, rows):
for j in range(0, col):
pixel = imgs[i, j]
for k in range(y.shape[0]):
if pixel == [k]:
my_nlist[k].append(pixel)
Don't make it harder on yourself than you have to :) this is exactly what a histogram is meant for!
import matplotlib.pyplot as plt
import cv2 as cv # You won't be needing cv2, it is just needed to create this example
img = cv.imread('dir/to/img', 0) # notice the grayscale flag
hist, bins, _ = plt.hist(img) # hist contains the list of pixels with the same intensity for each intensity in the picture
plt.show() # in case you want to visualize it
This is what it will look like:
Python: How to change a "penny" image color (copper) to different gray levels? Example given in image
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
plt.clf()
p = plt.imread ('penny.jpg')
plt.imshow(p)
penny = p.copy()
The conversion to grayscale code comes from https://stackoverflow.com/a/12201744/1092820
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# Import the image
p = plt.imread('penny.png')
# Convert to grayscale
gray = np.dot(p[...,:3],[0.299, 0.587, 0.114])
# Round gray to nearest 1/n, where n is how many grays:
grayCount = 4
roundedGray = np.floor(gray * float(grayCount)) / float(grayCount)
# Display using matplotlib's copper color mapping
plt.imshow(roundedGray, cmap=plt.get_cmap('copper'))
plt.show()
How can I convert the blue color of of the water in an image into white, especially if there are different shades of blue. And then separate any other color and give it for instance black. An example would be this pollution in the sea and you want to detect the contaminated area and give it a color clearly distinguishable from the water:
import cv2
import numpy as np
from matplotlib import pyplot as plt
BLUE = [255,0,0]
img1 = cv2.imread('11.jpg')
replicate = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REPLICATE)
reflect = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT)
reflect101 = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT_101)
wrap = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_WRAP)
constant=
cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_CONSTANT,value=BLUE)
plt.subplot(231),plt.imshow(img1,'gray'),plt.title('ORIGINAL')
plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE')
plt.subplot(233),plt.imshow(reflect,'gray'),plt.title('REFLECT')
plt.subplot(234),plt.imshow(reflect101,'gray'),plt.title('REFLECT_101')
plt.subplot(235),plt.imshow(wrap,'gray'),plt.title('WRAP')
plt.subplot(236),plt.imshow(constant,'gray'),plt.title('CONSTANT')
plt.show()
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
import numpy as np
from PIL import Image
import colorsys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
img = mpimg.imread('0.jpg')
gray = rgb2gray(img)
plt.imshow(gray, cmap = plt.get_cmap('gray'))
plt.show()
cv2.waitKey()
cv2.destroyAllWindows()