Displaying Hole Filled image in python with OpenCV - python

I am working on some image analysis in python using OpenCV. I want to display an image that I filled in holes with using scipy.ndimage.binary_filled_holes. Upon doing this I could not see anything being displayed when I used cv2.imshow, so I used plt.imshow and saw that the holes in my original image were filled. I want to use the cv2.imshow function to display the image. I did convert the image so that the datatype is uint8, yet still, nothing shows up. Any help would be appreciated.
import cv2
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage
img = cv2.imread('Funky 647.jpg', cv2.IMREAD_GRAYSCALE)
dst = cv2.fastNlMeansDenoising(img,None,10,7,21)
ret, thresh2 = cv2.threshold(dst, 40, 255, cv2.THRESH_BINARY)
hole_filled= np.uint8(scipy.ndimage.binary_fill_holes(thresh2))
# plt.imshow(hole_filled)
cv2.imshow('No Holes', hole_filled)
cv2.waitKey(0)
cv2.destroyAllWindows()
Hole Filled Image via matplotlib:

Related

cv2 in Python crashes when I try to open a 4 level CMYK numpy array

import numpy as np
from PIL import Image
import cv2
with Image.open("image.png") as im:
im = im.convert("CMYK")# not a true CMYK conversion here
im.show(title="image")
img = np.array(im)
#cv2.imshow('image', img)
I need to view a CMYK file hopefully using OpenCV and read pixel values in the CMYK space. I tried to load an image, convert it to CMYK(just 4 color levels) and view it using cv2. Note, I have cv2* commented out because it will cause Python to crash and OpenCv will need to be reinstalled. Will OpenCv allow me to view a (x, x, 0:3).uint8 numpy array? If so, throw me a line.
My solution was simple. I forgot the following:
cv2.waitKey(0)
cv2.destroyAllWindows()

Extract car images without Mask RCNN

I want to extract car images without using Mask RCNN. I tried a couple of methods but couldn't decide on how to proceed with any of them. I need recommendation on which method would be best and how to go through with it.
Method 1 - Using XML files and haar cascade classifier
I was thinking of using xml files to detection and crop car images. The problems I faced were:
They only detect car in square shapes. I needed car images cropped. So ultimately I ended up with better images of cropped cars. This didn't solve my problem.
The cropped image didn't detect car as a whole but small parts of it. Maybe due to XML file's config.
My code:
!wget https://raw.githubusercontent.com/shaanhk/New-GithubTest/master/cars.xml
import numpy as py
import cv2
car_cascade=cv2.CascadeClassifier('cars.xml')
img = cv2.imread('im1.jpg')
cars = car_cascade.detectMultiScale(img, 1.1, 1)
for (x,y,w,h) in cars:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Resulting image:
Method 2 - Using Canny Edge Detection
I tried to perform canny edge detection for car. It worked to some extent that I managed to reduce edges to mostly car object. But I don't know how to proceed from there.
My code:
import cv2
import numpy as np
image= cv2.imread('im1.jpg')
imagecopy= np.copy(image)
grayimage= cv2.cvtColor(imagecopy, cv2.COLOR_RGB2GRAY)
canny= cv2.Canny(grayimage, 300,150)
cv2.imshow('Highway Edge Detection Image', canny)
cv2.waitKey(0)
cv2.destroyAllWindows()
Resulting Image:
Method 3 - Extract car image using color gradients
On googling I found a method using HSV transformation and then creating a custom mask to extract cars. But I don't know much about this method and have no idea how to go about it. I used the code provided and am posting it below.
Code:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
image = mpimg.imread('im1.jpg')
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
# HSV channels
h = hsv[:,:,0]
s = hsv[:,:,1]
v = hsv[:,:,2]
background_hue = h[10,10]
lower_hue = np.array([background_hue-10,0,0])
upper_hue = np.array([background_hue+10,255,255])
mask = cv2.inRange(hsv, lower_hue, upper_hue)
# Mask the image to let the car show through
masked_image = np.copy(image)
masked_image[mask != 0] = [0, 0, 0]
cv2.imwrite('mask.jpg',masked_image)
# Display it!
plt.imshow(masked_image)
Image:
I'd like to mention, I'm a complete beginner in Computer Vision and am trying to learn by doing some small stuff like these. My code is probably very flawed and hopefully I can work on it on the way. Please feel absolutely free to mention any other method (except Mask RCNN) or any problems with code.

OpenCV not showing image in python

This is the code that I am using for OpenCV to display image. It only shows me a blank screen instead of showing a picture.
import cv2
# location and name of file is completely correct
img = cv2.imread("./Resources/img-2.jpg")
# Doesn't give a null so its okay
print(img.shape)
# suspecting that problem is here
cv2.imshow("preview", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
The image is stored in the right location and when I'm using a similar approach for a video and a webcam, it works perfectly.
The following is what the out is -
Try using matplotlib instead :
import matplotlib.pyplot as plt
import cv2
img = cv2.imread("./Resources/img-2.jpg")
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # convert img pixels to RGB format, so that matplotlib displays the image properly
plt.imshow(img)
plt.show()
If it still gives you a blank image, then the problem might come from your file or filename.

cv2.cvtcolor bgr2gray seems get an error image

# the code is as follows, implemented, but the result is possibly wrong, it is not the grayscale i wanted, someone gonna help me with that, it's seems quite simple, but i just don't know what wrong
import cv2
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.image as mpimg
img = cv2.imread('calibration_test.png')
# i want simply convert the rgb image to grayscale and then print it out
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(gray)
print(gray.shape)
# but the outcome is a colorful image
The grayscale conversion was done correctly. The problem is in how you are displaying the image. Try this:
plt.imshow(gray, cmap='gray')
By default imshow adds it's own colour key to single channel images, to make it easier to view. A typical example is thermal images which usually show blue and red, but all the colours are only dependend on one channel.
Hope this helps!

Creating an RGB picture in Python with OpenCV from a randomized array

I want to create a RGB image made from a random array of pixel values in Python with OpenCV/Numpy setup.
I'm able to create a Gray image - which looks amazingly live; with this code:
import numpy as np
import cv2
pic_array=np.random.randint(255, size=(900,800))
pic_array_8bit=slika_array.astype(np.uint8)
pic_g=cv2.imwrite("pic-from-random-array.png", pic_array_8bit)
But I want to make it in color as well. I've tried converting with cv2.cvtColor() but it couldnt work.
The issue might be in an array definition or a missed step. Couldn't find a similar situation... Any help how to make a random RGB image in color, would be great.
thanks!
RGB image is composed of three grayscale images. You can make three grayscale images like
rgb = np.random.randint(255, size=(900,800,3),dtype=np.uint8)
cv2.imshow('RGB',rgb)
cv2.waitKey(0)
First, you should define a random image data consisting of 3 channels using numpy as shown below-
import numpy as np
data = np.random.randint(0, 255, size=(900, 800, 3), dtype=np.uint8)
Now use, python imaging library as shown below-
from PIL import Image
img = Image.fromarray(data, 'RGB')
img.show()
You can also save the image easily using save function
img.save('image.png')

Categories

Resources