Here is the code that i'm trying to modify. To read and save all the images at once in one folder, however I got error when I tried to save it
import cv2
import glob
import numpy as np
#empty lists
image_list=[]
images = []
for img in glob.glob(r"C:\Users\user\Documents\Dataset\Test\Abnormal_Resize\Abnormal_Crop\*.png"):
n= cv2.imread(img)
images.append(n)
print (img)
#limit list to 236 elements
image_list = image_list[:100]
#Resizing the image for compatibility
for img in image_list:
image = cv2.resize(image, (500, 600))
#The initial processing of the image
#image = cv2.medianBlur(image, 3)
image_bw = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#The declaration of CLAHE
#clipLimit -> Threshold for contrast limiting
clahe = cv2.createCLAHE(clipLimit = 5)
final_img = clahe.apply(image_bw)
cv2.imwrite(path+r"C:\Users\user\Documents\Dataset\Test\Abnormal_Resize\Abnormal_Crop\Abnormal_Cntrst\contrast_"+str(i)+".png", final_img)
It seems like there are multiple issues with this code.
i is not defined.
images list has all the images appended and while processing you are making use of the empty list variable image_list
You are probably looking for a solution like this.
import cv2
import glob
import numpy as np
input_path = r"<your_input_folder_path>/*.png"
# make sure below folder already exists
out_path = '<your_output_folder_path>/'
image_paths = list(glob.glob(input_path))
for i, img in enumerate(image_paths):
image = cv2.imread(img)
image = cv2.resize(image, (500, 600))
#The initial processing of the image
#image = cv2.medianBlur(image, 3)
image_bw = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#The declaration of CLAHE
#clipLimit -> Threshold for contrast limiting
clahe = cv2.createCLAHE(clipLimit = 5)
final_img = clahe.apply(image_bw)
cv2.imwrite(out_path + f'{str(i)}.png', final_img)
Related
# organizing imports
import cv2
import numpy as np
import os
from PIL import ImageTk, Image
from os import listdir
from PIL import Image as PImage
# path to input image is specified and
# image is loaded with imread command
imagesdog = np.array([])
new_array = np.array([])
rootdirectory2 = os.listdir('alldata/data2/')
## Saves all images in directory to array from RGB values and resizes
for allimages in rootdirectory2:
image = Image.open('alldata/data2/' + allimages)
imagesave = np.asarray(image) ## Filters the image
smaller = cv2.resize(imagesave, (500, 500))
data = Image.fromarray(smaller)
IMG_SIZE = 500
xyz = cv2.resize(smaller, (IMG_SIZE, IMG_SIZE))
new_array = np.append(new_array, xyz)
## resized and appended, need to be added as a list
#cv2.imshow('Filtered', new_array[3])
for elements in new_array:
print(elements)
image1 = cv2.imread('alldata/data/image3.jpeg')
image1 = cv2.resize(image1, (500,500))
# cv2.cvtColor is applied over the
# image input with applied parameters
# to convert the image in grayscale
img = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
# applying different thresholding
# techniques on the input image
# all pixels value above 120 will
# be set to 255
ret, thresh1 = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img, 120, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img, 120, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img, 120, 255, cv2.THRESH_TOZERO_INV)
# the window showing output images
# with the corresponding thresholding
# techniques applied to the input images
print(len(new_array))
cv2.imshow('Binary Threshold', new_array[499])
cv2.imshow('Binary Threshold Inverted', thresh2)
cv2.imshow('Truncated Threshold', thresh3)
cv2.imshow('Set to 0', thresh4)
cv2.imshow('Set to 0 Inverted', thresh5)
# De-allocate any associated memory usage
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
I am working on a project where I intend to load in images, reduce them to their RGB values in a list and resize them, then add them to an array later to be filtered. Then reload them later on and be filtered.
Right know, I am struggling to get images separated. I have reduced to this for getting this accomplished. I keep getting an output of all the RGB values separated into 40600 elements and can't pull them out after initial appending.
Any help figuring out how I can get them to be added in [] and separated while being appending the resized versions, and returning the separated images in a multidimensional array?
Loading in using the same libraries, I couldn't resize them correctly. I reduced down to this method.
I want to extract numbers from captcha image, so I tried this code from this answer this answer:
try:
from PIL import Image
except ImportError:
import Image
import pytesseract
import cv2
file = 'sample.jpg'
img = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, None, fx=10, fy=10, interpolation=cv2.INTER_LINEAR)
img = cv2.medianBlur(img, 9)
th, img = cv2.threshold(img, 185, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4,8))
img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imwrite("sample2.jpg", img)
file = 'sample2.jpg'
text = pytesseract.image_to_string(file)
print(''.join(x for x in text if x.isdigit()))
and it worked fine for this image: outPut: 436359 But, when I tried it on this image: It gave me nothing, outPut: .
How can I modify my code to get the numbers as a string from the second image?
EDIT:
I tried Matt's answer and it worked just fine for the image above. but it doesn't recognise numbers like (8,1) in image A, and number (7) in image B
image A
image B
How to fix that?
Often, getting OCR just right on an image like this has to do with the order and parameters of the transformations. For example, in the following code snippet, I first convert to grayscale, then erode the pixels, then dilate, then erode again. I use threshold to convert to binary (just blacks and whites) and then dilate and erode one more time. This for me produces the correct value of 859917 and should be reproducible.
import cv2
import numpy as np
import pytesseract
file = 'sample2.jpg'
img = cv2.imread(file)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ekernel = np.ones((1,2),np.uint8)
eroded = cv2.erode(gray, ekernel, iterations = 1)
dkernel = np.ones((2,3),np.uint8)
dilated_once = cv2.dilate(eroded, dkernel, iterations = 1)
ekernel = np.ones((2,2),np.uint8)
dilated_twice = cv2.erode(dilated_once, ekernel, iterations = 1)
th, threshed = cv2.threshold(dilated_twice, 200, 255, cv2.THRESH_BINARY)
dkernel = np.ones((2,2),np.uint8)
threshed_dilated = cv2.dilate(threshed, dkernel, iterations = 1)
ekernel = np.ones((2,2),np.uint8)
threshed_eroded = cv2.erode(threshed_dilated, ekernel, iterations = 1)
text = pytesseract.image_to_string(threshed_eroded)
print(''.join(x for x in text if x.isdigit()))
I work with 3D volumes produced by confocal microscopy. These images have x,y,z dimensions around ~1024,1024,50 and are stored in a .tif file.
I want to apply OpenCV-python cv2.adaptiveThreshold to the whole image stack. The below code works well for a 2D image (1024,1024,1). How can I expand it for the whole volume and save the output .tif file?
img = cv2.imread("1024x1024x40.tif")
gimg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
th = cv2.adaptiveThreshold(gimg, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, -20)
cv2.imshow('original',img)
cv2.imshow('Adaptive threshold',th)
cv2.waitKey(0)
cv2.destroyAllWindows()
Thanks!
Using the bioformats package:
I don't have test data but using this answer as a guide, you might try something like the following:
import javabridge
import bioformats
javabridge.start_vm(class_path=bioformats.JARS)
path_to_data = '/path/to/data/file_name.tif'
xml_string = bioformats.get_omexml_metadata(path_to_data)
ome = bioformats.OMEXML(xml_string) # be sure everything is ascii
iome = ome.image(0) # e.g. first image
reader = bioformats.ImageReader(path_to_data)
raw_data = []
for z in range(iome.Pixels.get_SizeZ()):
img = reader.read(z=z, series=0, rescale=False)
gimg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
th = cv2.adaptiveThreshold(gimg, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, -20)
img = cv2.bitwise_and(img, img, mask = th)
raw_data.append(img)
bioformats.write_image("/path/to/data/file_name_OUTPUT.tif", raw_data)
I am segmenting an image and then converting it into HSV format. But after converting it into HSV and separating out each of the channels, the granularity of the segmented region is lost. Following is the segmentation code.
import cv2
from os import listdir
from os.path import isfile, join
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
path = "C:/Users/Intern/Desktop/dataset/rust images/"
files_test = [f for f in listdir(path+ 'Input/') if isfile(join(path+ 'Input/', f))]
for img_name in files_test:
img = cv2.imread(path + "Input/" + img_name)
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray_blur = cv2.GaussianBlur(gray_img, (7, 7), 0)
adapt_thresh_im = cv2.adaptiveThreshold(gray_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 20)
max_thresh, thresh_im = cv2.threshold(gray_img, 100, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
thresh = cv2.bitwise_or(adapt_thresh_im, thresh_im)
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)
sure_bg = cv2.dilate(thresh,kernel,iterations=2)
img[sure_bg == 0] = [0,0,0]
cv2.imwrite(path + "Segmented/" + img_name, img)
Following is the input image.
Following is the corresponding output.
Now, In a new program I try to read this output and convert it into HSV format. Following is the code.
import cv2
from os import listdir
from os.path import isfile, join
import numpy as np
path = "C:/Users/Intern/Desktop/dataset/rust images/"
files_test = [f for f in listdir(path+ "Segmented/") if isfile(join(path+ "Segmented/", f))]
for img_name in files_rust:
img = cv2.imread(path + "Segmented/" + img_name)
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
print img_hsv.shape
h, s, v = cv2.split(img_hsv)
cv2.imshow("hsv image", s)
cv2.waitKey(0)
Following is the output after converting into HSV.
We can observe that compared to the original one the granularity of the black spaces has reduced. How can I solve this problem?
Thanks for the help.
Photograph taken from 4
You code showed you applied GaussianBlur(), cv2.adaptiveThreshold() and cv2.morphologyEx(), all those filtering would likely make the details lost in some degree in the resulted image.
If you need to convert color space from BGR to HSV, cv2.cvtColor(img, cv2.COLOR_BGR2HSV), then you may just do minimal preprocessing to reduce the distortion before converting the image to HSV, and before you further any processing in HSV color space.
I was trying to skeletonize an image. Using this code, to an extent the image came out as I wanted. But still there are some issues in the image. I can find some gaps in between the lines. Is there any better alogorithm to get rid of those gaps.I have attached the input and the output of the given code.
import numpy as np
import cv2
img = cv2.imread("e_5.jpg",0)
size = np.size(img)
skel = np.zeros(img.shape,np.uint8)
ret,img = cv2.threshold(img,127,255,0)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
img = 255 - img
img = cv2.dilate(img, element, iterations=3)
done = False
while( not done):
eroded = cv2.erode(img,element)
temp = cv2.dilate(eroded,element)
temp = cv2.subtract(img,temp)
skel = cv2.bitwise_or(skel,temp)
img = eroded.copy()
zeros = size - cv2.countNonZero(img)
if zeros==size:
done = True