python failed to run script but successfully run line by line - python

when i run the code using Ipython3 it works.
but when I try to run it a python script via the terminal and getting the next error:
Traceback (most recent call last):
File "procces_image.py", line 3, in <module>
import mahotas as mh
File "/home/s/.local/lib/python3.6/site-packages/mahotas/__init__.py", line 83, in <module>
from . import polygon
File "/home/s/.local/lib/python3.6/site-packages/mahotas/polygon.py", line 8, in <module>
from . import _convex
ValueError: module functions cannot set METH_CLASS or METH_STATIC
import cv2
import pylab
import mahotas as mh
import matplotlib.pyplot as plt
from PIL import Image
path = '2_1.tif'
image = mh.imread(path)
im = Image.open(path)
img = Image.new('P', (1024, 1024))
img.paste(im)
pylab.imshow(img)
pylab.show()
print(image.shape)
im = mh.gaussian_filter(im, 4)
im = im.astype('uint8')
ret,thresh = cv2.threshold(im,130,255,0)
T = mh.thresholding.otsu(im)
labeled,nr_objects = mh.label(im > T)
labeled = labeled.astype('uint8')
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
pylab.imshow(im)
pylab.show()
im1 = Image.open(path)
im1.paste(im)
pylab.show()
the computer was recently formatted.
And all the packages are updated.
the code was originally created in Visual Studio code.

for some reason the matplotlib didn't work well with the mahotas
I neened to reinstall matplotlib using
sudo -H apt-get install python3-matplotlib

Related

How to get set of colours in an processed image using python PIL

I have an image and when I process it, I canĀ“t get the colors.
Here is my code:
import cv2
from PIL import Image
im = Image.open ('imag.jpg')
ret,thresh1 = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
from collections import defaultdict
by_color = defaultdict(int)
for pixel in thresh1.getdata():
by_color[pixel] += 1
print (by_color)
If I run just the original image (im), works well. But when I run processed image (thresh1), the following error appears:
Traceback (most recent call last):
File "file.py", line 62, in <module>
ret,thresh1 = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
TypeError: Expected cv::UMat for argument 'src'
For this function:
ret,thresh1 = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
to work you should read image using cv2.imread (returns numpy.array) rather than PIL.Image.open (returns Image object).

OSError: cannot identify image file 'file_name'

I have already read answer of this question Image.open() cannot identify image file - Python?, that question was solved by using from PIL import Image, but my situation is different. I am using image_slicer, and there I am getting these errors:
Traceback (most recent call last):
File "image_slice.py", line 17, in <module>
j=image_slicer.slice('file_name' , n_k)
File "/home/user_name/.local/lib/python3.5/site-
packages/image_slicer/main.py", line 114, in slice
im = Image.open(filename)
File "/home/user_name/.local/lib/python3.5/site-packages/PIL/Image.py", line 2687, in open
% (filename if filename else fp))
OSError: cannot identify image file 'file_name'
The full code is:
import os
from PIL import Image
import image_slicer
import numpy as np
import nibabel as nib
img = nib.load('/home/user_name/volume-20.nii')
img.shape
epi_img_data = img.get_data()
#epi_img_data.shape
n_i, n_j, n_k = epi_img_data.shape
center_i = (n_i - 1) // 2
center_j = (n_j - 1) // 2
center_k = (n_k - 1) // 2
centers = [center_i, center_j, center_k]
print("Co-ordinates in the voxel array: ", centers)
#for i in range(n_k):
j=image_slicer.slice('/home/user_name/volume-20.nii' , n_k)
However nib.load(), works fine, but image_slicer is not working.
All the nii images are 3D images.
Image slicer is not intended for reading nii format. Here is the list of supported formats.
This error also occurs whenever the image file itself is corrupted. I once accidentally was in the process of deleting the subject image, until canceling mid-way through.
TL;DR - open image file to see if it's ok.

Python Image to Text

i'm trying to write a python script that will take an image as an input and print out whatever is in the image as text to the terminal or a file. i do have python 2.7 and 3.7
i do have PIL and pytesseract install on my Kali linux
but i'm getting this errors
Traceback (most recent call last):
File "imgtotxt.py", line 8, in <module>
img =Image.open("/home/Desktop/ITT/1.jpeg")
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2609, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '/home/Desktop/ITT/1.jpeg'
HERE IS MY CODE
#!/usr/bin/python
from PIL import Image
from pytesseract import image_to_string
img =Image.open("/home/Desktop/ITT/1.jpeg")
text =image_to_string(img)
print (text)
Something is wrong with how you typed the filename.
Try this in your python code:
import os
print(os.listdir("/home/Desktop/ITT/"))
You should see your filename printed. Copy the filename from there instead.
If this fails, go up a directory (eg /home/Desktop) and try that.
Make sure if the file exists at the exact location you specified. The system isn't finding the file. Perhaps it's at /home/YOUR_USER/Desktop/ITT/1.jpeg ?
Put the script in the same folder as is the image, change path to only a name of the image and you will se if something is REALLY wrong.
EDIT:
Try this then:
import cv2
import numpy as np
image = cv2.imread('1.jpeg') # alternativly /home/Desktop/ITT/
img = Image.fromarray(image.astype(np.uint8))
....
Also check if your image is not corrupted. This is pretty strange

"ValueError: cannot filter palette images" during Pytesseract Conversion

Having trouble with this error code regarding the following code for Pytesseract. (Python 3.6.1, Mac OSX)
import pytesseract
import requests
from PIL import Image
from PIL import ImageFilter
from io import StringIO, BytesIO
def process_image(url):
image = _get_image(url)
image.filter(ImageFilter.SHARPEN)
return pytesseract.image_to_string(image)
def _get_image(url):
r = requests.get(url)
s = BytesIO(r.content)
img = Image.open(s)
return img
process_image("https://www.prepressure.com/images/fonts_sample_ocra_medium.png")
Error:
/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/g/pyfo/reddit/ocr.py
Traceback (most recent call last):
File "/Users/g/pyfo/reddit/ocr.py", line 20, in <module>
process_image("https://www.prepressure.com/images/fonts_sample_ocra_medium.png")
File "/Users/g/pyfo/reddit/ocr.py", line 10, in process_image
image.filter(ImageFilter.SHARPEN)
File "/usr/local/lib/python3.6/site-packages/PIL/Image.py", line 1094, in filter
return self._new(filter.filter(self.im))
File "/usr/local/lib/python3.6/site-packages/PIL/ImageFilter.py", line 53, in filter
raise ValueError("cannot filter palette images")
ValueError: cannot filter palette images
Process finished with exit code 1
Seems simple enough, but is not working. Any help would be greatly appreciated.
The image you have is a pallet-based image. You need to convert it to a full RGB image in order to use the PIL filters.
import pytesseract
import requests
from PIL import Image, ImageFilter
from io import StringIO, BytesIO
def process_image(url):
image = _get_image(url)
image = image.convert('RGB')
image = image.filter(ImageFilter.SHARPEN)
return pytesseract.image_to_string(image)
def _get_image(url):
r = requests.get(url)
s = BytesIO(r.content)
img = Image.open(s)
return img
process_image("https://www.prepressure.com/images/fonts_sample_ocra_medium.png")
You should also note that the the .convert() and .filter() methods return a copy of the image, they don't change the existing image object. You need to assign the return value to a variable as shown in the code above.
NOTE: I don't have pytesseract, so I can't check the last line of process_image().

Python cv2 MSER not working

I have installed cv2 (opencv-3.0.0) on my Windows machine, but unable to access MSER class:
import cv2
cv2.MSER()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'MSER'
For cv2 installation, I downloaded and extracted opencv-3.0.0.0.exe and then copied cv2.pyd to Ananconda sitepackage directory.
I see couple of post on internet about using cv2.MSER, but I can't figure out what is the issue with my cv2.
I was refering opencv-2.4 way of using MSER. From opencv-3.0.0 documentation, it appears that I need to use following:
cv2.MSER_create()
cam = video.create_capture(video_src)
mser = cv2.MSER_create()
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
vis = img.copy()
regions = mser.detectRegions(gray, None)

Categories

Resources