Unable to load image into window using cv2.Imshow - python

I have been attempting to produce an OCR tool following this tutorial on youtube, and using the following script:
import os
import sys
import cv2
import numpy as np
input_f = 'letter.data'
img_resize_factor = 12
start, end = 6, -1
height, width = 16, 8
with open(input_f, 'r') as f:
for line in f.readlines():
data = np.array([255*float(x) for x in line.split('\t')[start:end]])
img = np.reshape(data, (height, width))
img_scaled = cv2.resize(img, None, fx=img_resize_factor, fy=img_resize_factor)
print(line)
cv2.imshow('img', img_scaled)
c = cv2.waitKey()
if c == 27:
break
The code falls over when attempting to use cv2.imshow('img', img_scaled) the window appears however is non responding and the image is not loaded into it.
I am using the most up to date version of OpenCV, I am running this in VisualStudio, and have had to add "python.linting.pylintArgs": ["--extension-pkg-whitelist=cv2"] to the user settings.
The error I get is:
Exception has occurred: cv2.error OpenCV(4.0.0)
c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:261:
error: (-2:Unspecified error) in function '__cdecl
cv::CvtHelper,struct cv::Set<3,4,-1>,struct
cv::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class
cv::_OutputArray &,int)' > Unsupported depth of input image: >
'VDepth::contains(depth)' > where > 'depth' is 6 (CV_64F) File
"C:\Users\aofarrell\Desktop\Python\NeuralNetworks\SimpleOCR.py", line
23, in
break

Everything in your script is wrong.
Solution
1) If you are opening a file, open just file, get data and get out of with statement
2) The error you are experiencing is due to wrong shape
I opened the file and extracted images
import os
import sys
import cv2
import numpy as np
input_f = 'letter.data'
start, end = 6, -1
def file_opener(input_f):
with open(input_f,'r') as fl:
for line in fl.readlines():
yield np.array([255*float(x) for x in line.split('\t')[start:-1]])
iterator = file_opener(input_f)
images = np.array([row for row in iterator]).reshape(52152,16,8) # array with 52152 images
for image_index in range(images.shape[0]):
IMAGE = cv2.resize(images[image_index,:],(0,0),fx=5,fy=5)
cv2.imshow('image {}/{}'.format(image_index,images.shape[0]),IMAGE)
cv2.waitKey(0)
cv2.destroyAllWindows(0)

Related

flag = str(input()) EOFError: EOF when reading a line

I'm a beginner in this field and trying to make a gradio project of detecting similar image.
Here's my code -
import gradio as gr
from DeepImageSearch import Index, LoadData,SearchImage
import os;
def similar(input_img):
image_list = LoadData().from_folder(["C:/Users/HP/Pictures/abc"])
Index(image_list).Start()
img=SearchImage().get_similar_images(image_path=os.path.abspath(input_img))
return img
demo = gr.Interface(similar, gr.Image(shape=(200, 200)), "image")
demo.launch()
error I am getting

How can I capture detected image by Yolov4

I want to capture the box recognized while using YOLOv4 webcam recognition.
So i used this code.
import cv2
import detect as dt
from darknet import Darknet
from PIL import Image
vidcap = cv2.VideoCapture(0)
success, image = vidcap.read()
count = 0
m = Darknet('darknet/data/yolo-obj.cfg')
m.load_weights('darknet/backup/yolo-obj_30000.weights')
use_cuda = 1
m.cuda()
while success:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
im_pil = Image.fromarray(image)
im_pil = im_pil.resize((m.width, m.height))
boxes = dt.do_detect(m, im_pil, 0.5, 0.4, use_cuda)
result = open('Desktop/captureyolobox/capture%04d.jpg'%(count), 'w')
for i in range(len(boxes)):
result.write(boxes[i])
count = count + 1
success, image = vidcap.read()
result.close()
I've encountered this problem. I surfed the web to solve the problem, but I couldn't find it. Can you help me?
Traceback (most recent call last):
File "yoloshort.py", line 2, in <module>
import detect as dt
ImportError: No module named detect
Do you mean detect_image in darknet.py? You can check the darknet.py which have you want or not.

I can't make this to work, program that transforms an image into ASCII art

I just want Help with my code because I can't make it work properly.
The part where I am struggling is when the image is being resized to 300x300.
When I upload an image less than 300x300 it works like a charm, but when the image needs to be resized it shows that :
Traceback (most recent call last):
File "C:\Users\KAYL\Documents\Python\ASCII\ascii.py", line 20, in <module>
value = image_nb.getpixel((x, y))
File "C:\Users\KAYL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\Image.py", line 1315, in getpixel
return self.im.getpixel(xy)
IndexError: image index out of range
I just want the variable image_original to be resized and saved to image
Here's my code :
import io
import easygui
from resizeimage import resizeimage
import webbrowser
image_path = easygui.fileopenbox()
image_original = Image.open(image_path)
largeur, hauteur = image_original.size
image = resizeimage.resize_thumbnail(image_original, [300, 300])
output = io.StringIO()
image_nb = image.convert('L')
for y in range(hauteur):
for x in range(largeur):
value = image_nb.getpixel((x, y))
if value < 64:
output.write('#')
elif value < 128:
output.write('#')
elif value < 192:
output.write('/')
else :
output.write(',')
output.write('\n')
with open('image finale.txt', mode='w') as f:
print(output.getvalue(), file=f)
webbrowser.open("image finale.txt")

Adjusting size of barcode image output

I am trying to adjust the size of a barcode output
import barcode
from barcode.writer import ImageWriter
bar_class = barcode.get_barcode_class('code128')
barcode = '1234567890'
writer=ImageWriter()
writer.set_options({module_width:2, module_height:2})
code128 = bar_class(barcode, writer)
code128.save('filename')
The error I am getting is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'module_width' is not defined
I dont really understand how to use the documentation found here: https://pythonhosted.org/pyBarcode/writers/index.html
After you generated an image of any size you can resize it using PIL
import barcode
from barcode.writer import ImageWriter
import PIL
from PIL import Image
bar_class = barcode.get_barcode_class('code128')
barcode = '1234567890'
writer=ImageWriter()
code128 = bar_class(barcode, writer)
code128.save('filename') # save the originally generated image
to_be_resized = Image.open('filename.png') # open in a PIL Image object
newSize = (500, 300) # new size will be 500 by 300 pixels, for example
resized = to_be_resized.resize(newSize, resample=PIL.Image.NEAREST) # you can choose other :resample: values to get different quality/speed results
resized.save('filename_resized.png') # save the resized image
more on PIL.Image.resize
I solved this problem by changing this line
code128.save('filename', {"module_width":0.35, "module_height":10, "font_size": 18, "text_distance": 1, "quiet_zone": 3})
without using another liabrary.
See that!
I solved my problem exactly like this, when saving, I did it as follows::
IMPORTANT: Without another library!
ean = barcode.get('ean13', setbarcodehere, writer=ImageWitoutTextWriter())
filename = ean.save(setfilenamehere, {"module_width":0.35, "module_height":10, "font_size": 18, "text_distance": -3, "quiet_zone": 1})
filename
print('Done! :D, {}'.format(filename))
Example:

Python: How to format series of images to all fit on A4 page?

I am working on an art project and am converting text to binary to images.
So far, I have what I think is the hard part done and am almost there ...
except i'm not quite sure how to approach this last bit of the problem:
I have a series of images displayed one after another but I need to wrap the images so that they are formatted to all fit on a page of A4 (printer paper) in landscape orientation.
How should I approach this?
I have the basic script to convert text to binary to images.
One additional issue I'm seeing is that when I run the script on the entire passage, too many files are opened and I receive an error(shown below):
Traceback (most recent call last):
File "ascii_to_binary.py", line 73, in <module>
imgs = [Image.open(i) for i in list_im]
File "/home/odroid/.virtualenvs/cv/local/lib/python2.7/site-packages/PIL/Image.py", line 2410, in open
fp = builtins.open(filename, "rb")
IOError: [Errno 24] Too many open files: 'open_circle.png'
Here's the script in its entirety for reference:
import numpy as np
import cv2
import imutils
import sys
from PIL import Image
open_circle = 'open_circle.png'
closed_circle = 'closed_circle.png'
diamond = 'diamond.png'
text1 = open("filename.text", "r")
letters = text1.read()
a = len(letters)
binary_text = [None]*a #pre-allocating a list
encoded_bin = ' '.join([bin(ord(letter))[2:].zfill(8) for letter in letters])
b = len(encoded_bin[0:18])
list_im = [0]*b
for val in range(b):
if encoded_bin[val] == '0':
list_im[val] = closed_circle
if encoded_bin[val] == '1':
list_im[val] = open_circle
if encoded_bin[val] == ' ':
list_im[val] = diamond
imgs = [Image.open(i) for i in list_im]
min_shape = sorted( [(np.sum(i.size), i.size) for i in imgs] )[0][1]
imgs_comb = np.hstack( (np.asarray(i.resize(min_shape)) for i in imgs) )
imgs_comb = Image.fromarray(imgs_comb)
imgs_comb.show()

Categories