Open CV syntax in google colab - opencv

In the following code, I was trying to print the normalized image, which worked well in the google Colab environment. But as soon as I converted that image matrix to a flattened matrix it simply resulted in an error.
import cv2
import numpy as np
import matplotlib.pyplot as plt
from google.colab.patches import cv2_imshow
%matplotlib inline
import os
vertical = cv2.imread("vertical (1).PNG", cv2.IMREAD_GRAYSCALE)
horizontal = cv2.imread("horizontal (1).PNG", cv2.IMREAD_GRAYSCALE)
vertical = vertical/255
horizontal = horizontal/255
print(vertical)
print(horizontal)
vertical_flattened = vertical.flatten()
horizontal_flattened = horizontal.flatten()
print(vertical_flattened)
print(horizontal_flattened)
plt.rcParams["figure.figsize"]=(20,10)
plt.subplot(2,3,1)
plt.title('Vertical Image')
plt.imshow(vertical, cmap = 'gray')
plt.subplot(2,3,4)
plt.title('Vertical_flattened Image')
plt.imshow(vertical_flattened, cmap = 'gray')
plt.subplot(2,3,2)
plt.title('Horizontal Image')
plt.imshow(horizontal, cmap = 'gray')
cv2.waitKey(0)
The error details are as follows :
TypeError Traceback (most recent call last)
<ipython-input-9-c30222345864> in <module>
25 plt.subplot(2,3,4)
26 plt.title('Vertical_flattened Image')
---> 27 plt.imshow(vertical_flattened, cmap = 'gray')
28
29 plt.subplot(2,3,2)
TypeError: Invalid shape (61746,) for image data
What should I do to print the flattened image? Thanks in advance.

Related

I want to use cv2_imshow in colab

import cv2 as cv
import numpy as np
from google.colab.patches import cv2_imshow
from tensorflow.keras.models import load_model
img_color = cv.imread('test3.jpg', cv.IMREAD_COLOR)
img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY)
ret,img_binary = cv.threshold(img_gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
kernel = cv.getStructuringElement( cv.MORPH_RECT, ( 5, 5 ) )
img_binary = cv.morphologyEx(img_binary, cv. MORPH_CLOSE, kernel)
cv2_imshow('digit', img_binary)
cv.waitKey(0)
This is the process of training a model in handwritten and testing the trained model.
I want to load an image using imshow() in colab.
Is there any way to use it without setting the file path?
You can use matplotlib's function for it
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.gcf()
fig.set_size_inches(18, 10)
plt.axis("off")
plt.rcParams['figure.figsize'] = [20, 10]
plt.imshow(img_binary)
plt.show()

How to read RAW 12 image and save it as some readable format - JPG, GIF, PNG

Looking for a code or OS library to read RAW 12 using Java / C# / Python and to save in some common used format - JPG, GIF, PNG. Trying a following code:
import numpy
from PIL import Image
import rawpy
input_file = 'c:\\IdeaProjects\\raw12\\IT8-chart-15ms.raw12'
npimg = numpy.fromfile(input_file, dtype=numpy.uint16)
imageSize = (2048, 1536)
npimg = npimg.reshape(imageSize)
Exception has occurred: ValueError
cannot reshape array of size 9437184 into shape (2048,1536)
output_file = 'converted.tiff'
Image.fromarray(npimg/1023.0).save(output_file)
Image RAW12 source
The dimensions (2048, 1536) are not correct in your case, I tried 3072*3072 and here is the result:
import numpy as np
import matplotlib.pyplot as plt
input_file = "IT8-chart-5ms.raw12"
npimg = np.fromfile(input_file, dtype=np.uint16)
# print(npimg.shape)
imageSize = (3072,3072)
npimg = (npimg.reshape(imageSize)).astype(np.uint8)
plt.imshow(npimg, cmap='gray')
plt.axis('off')
plt.show()

Richardson-Lucy not sharpening image

I had posted a question previously about the Richardson-Lucy algorithm. I have a follow-up question I would appreciate help with.
Below is the Python code I am using. My input image is already blurry so I removed program lines that I originally had to intentionally blur the image. I am getting the error "RuntimeWarning: invalid value encountered in true_divide relative_blur = image / convolve(im_deconv, psf, mode='same')" I would appreciate help with debugging this. I kept the lines in the program that I commented out based on the suggestion below.
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageFilter
from scipy.signal import convolve2d as conv2
from skimage import color, data, restoration
Image.open('TOFA-003_UV_Cured_Lincoln_Corrected.bmp').convert('L').save('TOFA-003_UV_Cured_Lincoln_Corrected_gray.bmp')
astro = Image.open('TOFA-003_UV_Cured_Lincoln_Corrected_gray.bmp')
psf = np.ones((5, 5)) / 25
#psf = np.ones((8, 8)) / 25
astro = conv2(astro, psf, 'same')
astro = astro/255
# Add Noise to Image
#astro_noisy = astro.copy()
#astro_noisy += (np.random.poisson(lam=25, size=astro.shape) - 10) / 255
#astro_noisy = astro_noisy/255
# Restore Image using Richardson-Lucy algorithm
deconvolved_RL = restoration.richardson_lucy(astro, psf, iterations=2)
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(8, 5))
plt.gray()
for a in (ax[0], ax[1], ax[2]):
a.axis('off')
ax[0].imshow(astro)
ax[0].set_title('Original Data')
#ax[1].imshow(astro_noisy)
#ax[1].set_title('Noisy data')
ax[2].imshow(deconvolved_RL, vmin=astro.min(), vmax=astro.max())
ax[2].set_title('Restoration using\nRichardson-Lucy')
fig.subplots_adjust(wspace=0.02, hspace=0.2,
top=0.9, bottom=0.05, left=0, right=1)
plt.show()

Google Colab Upload error, how can you fix it? (Cannot read property '_uploadFiles' of undefined)

my problem is that I always get the following error when I operate the following code.Strange thing is that, when i set the epochs to 0 the error dosnt show up and I can upload with no problems. Thanks for the Help!
I have already tried anabling third party cockies, which did not help. The strange thing is, that the upload works, if I set the training epochs to 0.
Sometimes the error is google.colab._files is undefined.
I have already tried to use Chrome and Firefox.
import tensorflow as tf
import numpy as np
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images = training_images.reshape(60000, 28, 28, 1)
training_images = training_images / 255.0
test_images = test_images.reshape(10000, 28, 28, 1)
test_images = test_images / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32,(3,3),activation='relu', input_shape=(28,28,1)),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64,(3,3),activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(training_images,training_labels, epochs=1)
classes = model.predict(test_images)
predicted_classes = np.argmax(classes, axis=1)
print(classes[0])
print(test_labels[0])
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
import matplotlib.pyplot as plt
plt.imshow(test_images[0], cmap='Greys_r')
import numpy as np
from google.colab import files
from keras.preprocessing import image
import cv2
import matplotlib.pyplot as plt
uploaded = files.upload()
for fn in uploaded.keys():
path = '/content/' + fn
img = cv2.imread(path)
img = cv2.resize(img,(28,28))
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
x = image.img_to_array(img, dtype=np.float32)
print("top left pixel value:", x[0,0])
if x[0,0] > 250:
# white background
print("needs to be inverted!")
x -= 255
x *= -1
x = x / 255.0
x = x.reshape(1, 28, 28, 1)
plt.imshow(img, cmap='Greys_r')
plt.show()
classes = model.predict(x)
plt.bar(range(10), classes[0])
plt.show()
print("prediction: class", np.argmax(classes[0]))
TypeError: Cannot read property '_uploadFiles' of undefined
So I found out that it works if you use 2 cells one for the neural network and one for the upload feature.

I don't know opencv Error about code checking footsize

I want to make program checking my foot-size
I don't know this error about opencv
url: http://cocoding94.blogspot.com/2017/05/blog-post_7.html .
import numpy as np
import matplotlib.pyplot as plt
import cv2
img = cv2.imread("foot.jpeg")
blur = cv2.blur(img,(5,10))
rows,cols,ch = img.shape
pts1 = np.float32([170,270],[480,220],[240, 710],[540,650])
pts2 = np.float32([0,0],[210,0],[0,297],[210,297])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(210,297))
plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.plot(*zip(*point), marker='.', color='r', ls='')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()
In raspberry pi error printing:
Traceback (most recent call last): File "foot.py",line 7,in
blur = cv2. blur (img,(5,10)) cv2.error:OpenCV(3.4.3)
/home/pi/opencv/opencv-3.4.3/modules/core/src/matrix.cpp:756: error:
(-215:Assertion failed) dims <=2 && step[0] > 0 in function
'locateROI'
but please next time add more information to make this community greater than another, I fixed some errors in your code, i donĀ“t your original image, but the code now works well, try to change your point to get a good perspective:
import numpy as np
import matplotlib.pyplot as plt
import cv2
img = cv2.imread("machupichu.jpg")
#blur = cv2.blur(img,(5,5))
#rows,cols,ch = img.shape
point=[[170,270],[480,220],[240, 710],[540,650]]
pts1 = np.float32([[170,270],[480,220],[240, 710],[540,650]])
pts2 = np.float32([[0,0],[210,0],[0,297],[210,297]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(210,297))
plt.subplot(121)
plt.imshow(img)
plt.title('Input')
plt.plot(*zip(*point), marker='.', color='r', ls='')
plt.subplot(122)
plt.imshow(dst)
plt.title('Output')
plt.show()
Here is the image which I used:
Machu Pichu
This is the result:
Best Regards.

Resources