im7 image files to openCV - python

Able to show the image through matplotlib, however unable to do it through cv2.imshow. The shape of the image is not consistent with opencv required formats. Require help on changing on changing it so it can be shown by the command cv2.imshow
test.jpg is a random jpg file from web
import numpy as np
import cv2
import matplotlib.pyplot as plt
import ReadIM
img = cv2.imread('test.jpg')
vbuff, vatts = ReadIM.extra.get_Buffer_andAttributeList('test.im7')
v_array, vbuff = ReadIM.extra.buffer_as_array(vbuff)
print (np.shape(v_array))
print (v_array[0])
print (np.shape(img))
# Showing image through matplotlib
plt.imshow(v_array[0])
plt.show()
#Showing image through cv2
cv2.imshow('image',v_array[0])
cv2.waitKey(0)
cv2.destroyAllWindows()
# Remove memory
#del(vbuff)
ReadIM.DestroyBuffer(vbuff)
ReadIM.DestroyAttributeListSafe(vatts)
test.im7

Normalizing the image to (0,255) will do the trick
img = cv2.normalize(img, None, 255,0,cv2.NORM_MINMAX,dtype = cv2.CV_8UC1)
cv2.imshow('image',img)

Related

PIL won't load RGB Image

I am trying to load this image into python (I provided a link because its 75mb): https://drive.google.com/file/d/1usiKRN1JQaIxTTo_HTXPwUj8LeyR8CDc/view?usp=sharing
My current code is below, it loads the image and when you png.show() the image it displays it in RBG but when converted to a numpy array its shape is only (h, w) not (h, w, 3) for RGB.
Code:
import numpy as np
from PIL import Image
Image.MAX_IMAGE_PIXELS = 233280000
png = Image.open('world.png')
png.show()
png = np.array(png)
print(png.shape)
Try this instead:
import numpy as np
from PIL import Image
Image.MAX_IMAGE_PIXELS = 233280000
png = Image.open('world.png').convert('RGB')
png.show()
png = np.array(png)
print(png.shape)

Using Tesseract-OCR in Python to get number from images

I have thousands of scale images that I would like to extract the reading of the scale from each image. However, when using the Tesseract it gives wrong values. I tried several process for the image but still running to same issue. From my understanding so far after defining region of interest in the image, it has to be converted to white text with black background. However, I am new to python, I tried some functions to do so but still running to same issue. Would be appreciated if someone can help me on this one. The following link is for the image, as I couldn't uploaded it here as it is more than 2 MiB:
https://mega.nz/file/fZMUDRbL#tg4Tc2VmGMMdEpnZzt7blxZjVLdlhMci9jll0FLnIGI
import cv2
import pytesseract
import matplotlib.pyplot as plt
import numpy as np
import imutils
## Reading Image File
Filename = 'C:\\Users\\Abdullah\\Desktop\\Scale Reading\\' #File Path For Images
IName = 'Disk_Test_1_09_07-00000_0.tif' # Image Name
Image = cv2.imread(Filename + IName,0)
## Image Processing
Image_Crop = Image[1680:1890, 550:1240] # Define Region of Interest of the image
#cv2.imshow("cropped", Image_Crop) # Show Cropped Image
#cv2.waitKey(0) # Show Cropped Image
Mask = Image_Crop > 10 # Thershold Image to Value of X
Mask = np.array(Mask, dtype=np.uint8)
plt.imshow(Mask, alpha=1) # Set Opacity (Max 1)
ret,Binary = cv2.threshold(Mask,0,255,cv2.THRESH_BINARY)
#plt.imshow(Image_Crop, cmap="gray") # Transform Image to Gray
#plt.show()
plt.imshow(Binary,'gray',vmin=0,vmax=255)
plt.show()
## Number Recognition
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' # Call Location of Tesseract-OCR
data = pytesseract.image_to_string(Binary, lang='eng',config='--psm 6')
print(data)
Here is the image after processing

adding an overlay on a DICOM image using open CV

I am trying to create a layer on a DICOM image, below code works fine for jpg/png images but not for DICOM.
import cv2
import numpy as np
import pydicom as dicom
ds=dicom.dcmread('D0009.dcm')
img=ds.pixel_array
blank = np.zeros(shape=(img.shape[0],img.shape[1],3), dtype=np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(blank,
text='Logo',
org=(img.shape[1]//8, img.shape[0]//2),
fontFace=font,
fontScale= 2,color=(163,163,163),
thickness=11,
lineType=cv2.LINE_4)
blend=cv2.addWeighted(img,0.7,blank,1, 0, dtype = cv2.CV_32F)
cv2.imshow('sample image dicom',blend)
cv2.waitKey()
any help would be apreciated
I was able to get this working by normalizing the value range of the DICOM image and converting the DICOM image from greyscale to RGB image. Replace your line
img=ds.pixel_array
with these lines:
img = np.array(ds.pixel_array, dtype='float32')
img /= np.max(img)
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)

How to reshape png image read by skimage.imread

Then I read some jpg file, this way
image = imread('aa.jpg')
As result I get dataframe with numbers from 1 to 255
I can resize it this way:
from cv2 import resize
image = resize(image, (256, 256)
But then I doing same think with png, result not desired.
image = imread('aa2.png') # array with number within 0-1 range
resize(image, (256,256)) # returns 1 channel image
resize(image, (256,256, 3)) # returns 3 channel image
Weird image
But imshow(image)
cv2.imread reads the image in 3 channel by default instead of 4. Pass the parameter cv.IMREAD_UNCHANGED to read your PNG file and then try to resize it as shown in the code below.
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
img = cv.imread('Snip20190412_12.png', cv.IMREAD_UNCHANGED)
print(img.shape) #(215, 215, 4)
height, width = img.shape[:2]
res = cv.resize(img,(2*width, 2*height))
print(res.shape)#(430, 430, 4)
plt.imshow(res)
I guess is some problem with your image or code.
Here a free image to try: https://pixabay.com/vectors/copyright-free-creative-commons-98566/
Maybe you have problem with libpng, check this answers: libpng warning: iCCP: known incorrect sRGB profile
Check this simple code that works on PNG images.
import cv2 as cv
image = cv.imread("foto.png")
if __name__ == "__main__":
while True:
image = cv.resize(image,(200,200))
cv.imshow("prueba",image)
key = cv.waitKey(10)
if key == 27:
cv.destroyAllWindows()
break
cv.destroyAllWindows()

Image loaded wrong by opencv

Disaster!
As you can see, the image isn't quite loaded correctly. The original:
The code:
import cv2
import imutils
a=imutils.url_to_image("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png", readFlag=-1)
cv2.imshow("goog", a)
cv2.waitKey()
The implementation of url_to_image in imutils:
def url_to_image(url, readFlag=cv2.IMREAD_COLOR):
# download the image, convert it to a NumPy array, and then read
# it into OpenCV format
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, readFlag)
# return the image
return image
I also tried readFlag=cv2.IMREAD_UNCHANGED, but that didn't do the trick either.
please send help
alright gang we did it
so I tried another version of displaying:
plt.figure("Correct")
plt.imshow(imutils.opencv2matplotlib(a))
plt.show()
No luck it would appear. But then, looking into the opencv2matplotlib source, we find:
def opencv2matplotlib(image):
# OpenCV represents images in BGR order; however, Matplotlib
# expects the image in RGB order, so simply convert from BGR
# to RGB and return
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
Aha, but we have 4 channel color (alpha), so by common sense we need cv2.COLOR_BGRA2RGBA not cv2.COLOR_BGR2RGB!!
Testing this theory:
plt.figure("Correct")
plt.imshow(cv2.cvtColor(a, cv2.COLOR_BGRA2RGBA))
plt.show()
We get...
Whoop dee doop!
# import the necessary packages
import numpy as np
import urllib
import cv2
def url_to_image(url):
# download the image, convert it to a NumPy array, and then read
# it into OpenCV format
resp = urllib.request.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# return the image
return image
# initialize the list of image URLs to download
url="http://i.dailymail.co.uk/i/pix/2015/09/01/18/2BE1E88B00000578-3218613-image-m-5_1441127035222.jpg"
print ("downloading %s" % (url))
image = url_to_image(url)
cv2.imshow("Image", image)
cv2.waitKey(0)
And the output is:

Categories