cv2 imdecode returns none with base64 string - linux

When i try to convert base64 string into image i am getting none in CV2.
Following is my code
import cv2
import numpy as np
def bsae62toimage(imgvalue):
imge = "R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7"
nparr = np.fromstring(imge,np.uint8)
print(nparr.shape)
img1 = cv2.imdecode(nparr,cv2.IMREAD_UNCHANGED)
print(img1.shape)
It is printing the numpy array but cv2.imdecode is returning None. Can you help me to find the problem in my code?
My Findings: np.fromstring it returns 1D array. I assume it should it should return 3D array. But i may be wrong.

Since it is unclear as from where have you obtained the imge = "R0lGODlhEA..." variable. I would present an ideal flow for converting OpenCV image to base64 string and converting it back to OpenCV img as:
import cv2
import base64
import numpy as np
def to_base64(img):
_, buf = cv2.imencode(".png", img)
return base64.b64encode(buf)
def from_base64(buf):
buf_decode = base64.b64decode(buf)
buf_arr = np.fromstring(buf_decode, dtype=np.uint8)
return cv2.imdecode(buf_arr, cv2.IMREAD_UNCHANGED)
img = cv2.imread("/path/to/img.png")
img_base64 = to_base64(img)
img_decoded = from_base64(img_base64)
print img_decoded.shape
Also the documentation states that:
If the buffer is too short or contains invalid data, the empty
matrix/image is returned.
It seems to me that imge = "R0lGODlhEA..." is invalid.

Related

How to extract only CR No only from image

Sample image
I need to extract CR No.from the sample image given above. Using Easyocr, I got the output in complex nested list form. How to update the code to filter out all the detected text/numbers and get only CR No. I am running out of ideas, and help will be appreciated. What I have tried so far-
#Import libraries
import os
import easyocr
import cv2
from matplotlib import pyplot as plt
import numpy as np
IMAGE_PATH = 'H://CDAC//Spyder_projects//CR_No//input_image//input7.jpg'
reader = easyocr.Reader(['en'])
result3 = reader.readtext(IMAGE_PATH)
result3
my_list2 = []
length = len(result3)
for i in range(length):
if (result3[i][1]) == 'CR No':
print(result3[i])
print(result3[i+1])
my_list2.append(result3[i+1]+result3[i])
print(my_list2)
print('The CR No is:', my_list2[0][1])
The expected output should be- 211022203481161

how to pass an array instead of path in keras preprocessor

I want to convert an image that was loaded by cv2 into an specific format with keras preprocessor.
The keras.preprocessing.image.load_image() function takes input as path but i have only the numpy array.
I need help in converting the image into specfic format
The code i want to do is:
def convert(img):
img = load_img(imge, grayscale=True, target_size=(28, 28))
img = img_to_array(imge)
img = img.reshape(1, 28, 28, 1)
img = img.astype('float32')
img = img / 255.0
return img
Is there any other way to get the above format with numpy array and not with image path.
i got the output by the following method
import numpy as np
import cv2
img=cv2.imread('check.jpg')
grey=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
resized=cv2.resize(grey,(28,28))
np_arr=np.array(resized)
np_arr=np_arr.astype('float32')/255
print(np_arr.size)

Google Colab - AttributeError: 'numpy.ndarray' object has no attribute 'seek' and 'read'

I'm trying to concatenate 3 images horizontaly. I've found a way that seems good enough on the the internet, the problem is that I'm having two errors that I can't figure out how to fix.
Note: I'm using Google Colab with Python 3.
Here is the errors:
AttributeError: 'numpy.ndarray' object has no attribute 'seek'
AttributeError: 'numpy.ndarray' object has no attribute 'read'
My code:
import matplotlib.pyplot as plt
import numpy as np
import sys
import PIL
import cv2
rgb = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_1_3.tif")
tir = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_TIR_1_3.tif")
qb = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_QB_1_3.tif")
list_im = [rgb, tir, qb]
imgs = [ PIL.Image.open(i) for i in list_im ]
# pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here)
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 ) )
# save that beautiful picture
imgs_comb = PIL.Image.fromarray( imgs_comb)
imgs_comb.save( 'Trifecta.jpg' )
Apparently the error happens on this line: ---> 12| imgs = [ PIL.Image.open(i) for i in list_im ]
And because of it I tried to update the Pillow library to 5.3.0, but the error still happens, what should I do?
How about not using pil, seems like opencv can do want you want
import matplotlib.pyplot as plt
import numpy as np
import sys
import cv2
rgb = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_1_3.tif")
tir = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_TIR_1_3.tif")
qb = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_QB_1_3.tif")
list_im = [rgb, tir, qb]
# pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here)
min_width = min([img.shape[1] for img in list_im])
min_height = min([img.shape[0] for img in list_im])
list_img = [cv2.resize(img, (min_width, min_height)) for img in list_im]
imgs_comb = np.hstack( list_img )
# save that beautiful picture
cv2.imwrite('result.jpg', imgs_comb)

Sending matplotlib image to pymsteams (cannot create new tag pymsteams)

I am using matplotlib to plot my image.
import pandas as pd
from matplotlib import pyplot as plt
x = ['09:30', '09:33', '09:40', '09:43', '09:50', '09:53', '10:00', '10:03', '10:10', '10:13']
y = ['3010.910000', '3011.650000', '3009.130000', '3011.500000', '3010.460000', '3010.950000', '3012.830000', '3013.120000', '3011.730000', '3010.130000']
matrix = pd.DataFrame({'Time': x, 'Quote': y})
matrix['Quote'] = matrix['Quote'].astype(float)
plt.plot('Time', 'Quote', data=matrix, color='mediumvioletred')
Here is the challenge now:
import pymsteams
web_hook = 'My Microsoft Teams URL https://outlook.office.com/webhook/blahblah'
teams_message = pymsteams.connectorcard(web_hook)
msg_section = pymsteams.cardsection()
msg_section.title('Title')
msg_section.addImage(image) #I want to add that plt image here
teams_message.addSection(msg_section)
teams_message.text("Some Message")
self.teams_message.send()
I have tried this (and I want this approach, using cache):
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
msg_section.addImage(buf.read())
I did try saving the image to local drive 'c:/temp/'. The code did not give any error msg, but the image on Teams was a blank image, even though the image is correct in c:/temp
In summary. A PNG image has to be converted to base64 string.
Please see the example below.
Note that I'm using Python 3.6.
Additionally image width seems to be limited in a Connector Card.
import numpy as np
import matplotlib.pyplot as plt
import base64
from io import BytesIO
import pymsteams
# generate fig
fig, ax = plt.subplots(1,1,figsize=(20,6))
ax.hist(np.random.normal(0, 1, 1000), bins=51, edgecolor='k', alpha=0.5);
buf = BytesIO()
fig.savefig(buf, format="png")
# get base64 string
data = base64.b64encode(buf.getbuffer()).decode("ascii")
encoded_fig = f"data:image/png;base64,{data}"
# send encoded_fig via webhook
web_hook = 'YOUR_WEBHOOK'
teams_message = pymsteams.connectorcard(web_hook)
msg_section = pymsteams.cardsection()
msg_section.title('Title')
msg_section.addImage(encoded_fig) #I want to add that plt image here
teams_message.addSection(msg_section)
teams_message.text("Some Message")
teams_message.send()
image_file = open('img/icon.png'), "rb").read()
ICON = "data:image/png;base64,{data}".format(data=b64encode(image_file).decode("ascii"))
#And in your Teams alert creation, you call:
section.activityImage(ICON)

read all images from the folder and convert it to a single channel image and save it

I want to save the single channel image from RGB image When I take one image it will works but when I take multiple images the I got problem
from glob import glob
import os
import numpy as np
def load_data(path):
img_list = []
for img in glob(os.path.join(path,"*.jpeg")):
image = cv2.imread(img)
img_list.append(image)
return img_list
p = load_data(path)
path = 'F:/EyePac/eye/class/Train_1'
img_array = np.array(p)
rgb = img_array[1]
r = rgb_r.copy()
r[:,:,1]=0
r[:,:,2]=0

Resources