RuntimeError using cv.SaveImage in openCV - python

I want to convert a jpg file to png, but when I run this code :
from opencv import _cv
from opencv.highgui import cvSaveImage, cvLoadImage
cvSaveImage("bet.jpg",cvLoadImage("bet.jpg"))
if __name__ == '__main__':
pass
It gives this error which I don't understand :
Traceback (most recent call last):
File "convert.py", line 6, in <module>
cvSaveImage("bet.jpg",cvLoadImage("bet.jpg"))
File "/usr/lib/pymodules/python2.6/opencv/highgui.py", line 183, in cvSaveImage
return _highgui.cvSaveImage(*args)
RuntimeError: openCV Error:
Status=Null pointer
function name=cvGetMat
error message=NULL array pointer is passed
file_name=cxarray.cpp
line=2780
I have my picture with the same folder of source code and the name of the image is bet.jpg
Any idea ??

The best choice is pyopencv:
import pyopencv as cv
img = cv.imread('01.png')
cv.imshow('img-windows',img)
cv.waitKey(0)
cv.imwrite('01.png',img)

From Python CV documentation, the CV2 method for converting a jpeg to png is:
Python: cv2.imwrite(filename, img[, params]) → retval
For my example:
import cv2
filename = 'pic.jpeg'
cam = cv2.VideoCapture(filename)
s, img = cam.read()
picName = 'pic.png'
cv2.imwrite(picName, img)
VideoCapture is nice and general, and works with videos, webcams and image files.

I solved the problem, the image I took randomly from the Google Images doesn't load. Maybe it's encrypted or something I don't know. I tried it with other images, and worked very well. So watch out while copying images : )

Related

OpenCV QRCodeDetector Out Of Memory even with a small file

So I'm trying to decode a QR code image using code from this S.O. answer. Here's the adapted code:
import cv2
# Name of the QR Code Image file
filename = r"C:\temp\2021-12-14_162414.png"
# read the QRCODE image
image = cv2.imread(filename)
# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()
# detect and decode
data, vertices_array, binary_qrcode = detector.detectAndDecode(image)
# if there is a QR code
# print the data
if vertices_array is not None:
print("QRCode data:")
print(data)
else:
print("There was some error")
(This is the whole program; I was still experimenting.)
The PNG file itself is really small, just 43 KB in size, with resolution of 290x290 (24 bpp) containing just the QR Code.
However, I keep getting the error:
Traceback (most recent call last):
File "C:/Repos/tesqr/decod-cv2.py", line 10, in <module>
data, vertices_array, binary_qrcode = detector.detectAndDecode(image)
cv2.error: OpenCV(4.5.4) D:\a\opencv-python\opencv-python\opencv\modules\core\src\alloc.cpp:73: error: (-4:Insufficient memory) Failed to allocate 54056250000 bytes in function 'cv::OutOfMemoryError'
Why is alloc.cpp asking for 54 GB of RAM ???
I'm new with OpenCV, so please help me troubleshoot what went wrong.
The library I'm using is:
$ pip3 freeze | grep opencv
opencv-contrib-python-headless==4.5.4.60
the input image:
Short Answer:
Try WeChatQRCode
Long Answer:
There are several open memory issues about decoding with QRCodeDetector. I hope that in future versions it will be fixed. Meanwhile you can try WeChatQRCode also from cv2.
WeChatQRCode includes two CNN-based models: A object detection model and a super resolution model. Object detection model is applied to detect QRCode with the bounding box. super resolution model is applied to zoom in QRCode when it is small.
Your code modified:
import cv2
# Name of the QR Code Image file
filename = "2021-12-14_162414.png"
# read the QRCODE image
image = cv2.imread(filename)
# initialize the cv2 QRCode detector
detector =cv2.wechat_qrcode_WeChatQRCode(detector_prototxt_path = "detect.prototxt", detector_caffe_model_path = "detect.caffemodel", super_resolution_prototxt_path = "sr.prototxt", super_resolution_caffe_model_path = "sr.caffemodel")
# detect and decode
data, vertices_array = detector.detectAndDecode(image)
# if there is a QR code
# print the data
if vertices_array is not None:
print("QRCode data:")
print(data)
else:
print("There was some error")
Output:
QRCode data:
('PK\x03\x04\n',)
As you can see, it needs prototxt and caffemodel files. You can find them here.

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).

Inserting icc color profile into image using Pillow ImageCMS

I am trying to insert an ICC color profile into an image. Using code from this post as an example my code looks like this:
from PIL import Image, ImageCms
# Read image
img = Image.open(IMG_PATH)
# Read profile
profile = ImageCms.getOpenProfile(PROFILE_PATH)
# Save image with profile
img.save(OUT_IMG_PATH, icc_profile=profile)
I get the following error
Traceback (most recent call last):
File "/home/----/Documents/code_projects/hfss-misc/icc_profiles/insert_icc_profile_into_image.py", line 17, in <module>
img.save(OUT_IMG_PATH, icc_profile=srgb_profile)
File "/home/----/.virtualenvs/color-correction/lib/python3.6/site-packages/PIL/Image.py", line 2102, in save
save_handler(self, fp, filename)
File "/home/----/.virtualenvs/color-correction/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 706, in _save
markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER])
TypeError: 'PIL._imagingcms.CmsProfile' object is not subscriptable
I thought that there might be a problem with my ICC profile so I tried to use one generated by Pillow.
from PIL import Image, ImageCms
# Read image
img = Image.open(IMG_PATH)
# Creating sRGB profile
profile = ImageCms.createProfile("sRGB")
# Save image with profile
img.save(OUT_IMG_PATH, icc_profile=profile)
I still get the same error, however.
Does anyone know what the cause for this error is?
My system environment is as follows:
Ubuntu 18.04
Python 3.6
Pillow==7.0.0
The answer from github at (https://github.com/python-pillow/Pillow/issues/4464) was to use profile.to_bytes():
img.save(OUT_IMG_PATH, icc_profile=profile.tobytes())

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

Categories

Resources