Here i'm trying to:
- Apply Adaptive filtering to image .
- Enhance the contrast of image .
my code is as follow :
#!/usr/bin/python
import cv2
import numpy as np
import PIL
from PIL import ImageFilter
from matplotlib import pyplot as plt
img = cv2.imread('Crop.jpg',0)
cv2.imshow('original',img)
img = cv2.medianBlur(img,5)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,11,2)
cv2.imshow('image',th3)
th3 = th3.filter(ImageFilter.SMOOTH)
cv2.imshow('image',th3)
cv2.waitKey(0)
cv2.destroyAllWindows()
I am getting following Error :
Traceback (most recent call last):
File "./adaptive.py", line 22, in
th3 = th3.filter(ImageFilter.SMOOTH)
AttributeError: 'numpy.ndarray' object has no attribute 'filter
You may confuse with cv.Smooth
Related
I have tried to convert an RGB image to Otsu binary image (gray scale) but that doesn't seem to work as I get the error as mentioned below.
from cv2 import cv2
import numpy as np
from skimage.color import rgb2gray
from skimage.filters import threshold_otsu
from skimage.io import imread
from skimage.morphology import skeletonize
from skimage.util import invert
import matplotlib.pyplot as plt
img = rgb2gray(imread('Ared.png'))
binary = img > threshold_otsu(img)
np.unique(binary)
skeleton = skeletonize(invert(binary))
cv2.imshow('original', img)
cv2.imshow('skeleton', skeleton)
cv2.waitKey(0)
cv2.destroyAllWindows()
Result in terminal
img = rgb2gray(imread('Ared.png'))
Traceback (most recent call last):
File "preprocessing.py", line 16, in <module>
cv2.imshow('skeleton', skeleton)
TypeError: Expected Ptr<cv::UMat> for argument '%s'
Your format is wrong. You need to change it to float32. That's a common error with opencv. You can change this line to convert it to float32 and it should work fine.
cv2.imshow('skeleton', np.float32(skeleton))
Bad exception messages are bad...
cv2.imshow does not handle binary arrays. The acceptable types according to this answer are uint8, uint16, int, float, and double.
you should be able to convert the array to uint8 with:
skeleton.astype('u1')
This will leave you with values between 0 and 1 though, which is all very dark. If you the multiply the array by 255, the colors should be black and white as expected:
skeleton.astype('u1') * 255
full example with data image from skimage:
from cv2 import cv2
from skimage.filters import threshold_otsu
from skimage.morphology import skeletonize
from skimage.util import invert
from skimage.data import camera
img = camera()
binary = img > threshold_otsu(img)
skeleton = skeletonize(invert(binary))
cv2.imshow('original', img)
cv2.imshow('skeleton', skeleton.astype('u1')*255)
cv2.waitKey(0)
cv2.destroyAllWindows()
I applied Image deconvolution using an unsupervised wiener algorithm and increased the sharpness and contrast on a specific dataset. But I faced an error while compiling the code. It shows AttributeError: 'numpy.ndarray' object has no attribute 'convert'. How to fix it? My code is given below -
import cv2
import glob
from matplotlib import pyplot as plt
from skimage import io, color, restoration, img_as_float
import scipy.stats as st
import numpy as np
from PIL import Image
from PIL import ImageEnhance
all_img = glob.glob('input/*.png')
other_dir = 'output/'
for img_id, img_path in enumerate(all_img):
img = img_as_float(io.imread(img_path,0))
def gkern(kernlen=21, nsig=2):
lim = kernlen//2 + (kernlen % 2)/2
x = np.linspace(-lim, lim, kernlen+1)
kern1d = np.diff(st.norm.cdf(x))
kern2d = np.outer(kern1d, kern1d)
return kern2d/kern2d.sum()
psf = gkern(5,3)
deconvolved, _ = restoration.unsupervised_wiener(img, pdf)
# Applied Sharpness and contrast
enhancer_object = ImageEnhance.Contrast(deconvolved)
out = enhancer_object.enhance(1.4)
enhancer = ImageEnhance.Sharpness(out)
enhanced_im = enhancer.enhance(8.0)
enhanced_cv_im = np.array(enhanced_im)
cl2 = cv2.resize(enhanced_cv_im, (512,512), interpolation = cv2.INTER_CUBIC)
plt.imsave(f"output/unsupervised_wiener_{img_id}.png", cl2, cmap='gray')
It shows the error-
runfile('C:/Users/Junaed/.spyder-py3/unsupervised_wiener.py', wdir='C:/Users/Junaed/.spyder-py3')
Traceback (most recent call last):
File "C:\Users\Junaed\.spyder-py3\unsupervised_wiener.py", line 37, in <module>
enhancer_object = ImageEnhance.Contrast(deconvolved)
AttributeError: 'numpy.ndarray' object has no attribute 'convert'
ImageEnhance.Contrast() is expecting a PIL image which it can run image.convert on but you passed it a numpy array. To convert to PIL you can do this
from PIL import Image
import numpy
im = Image.fromarray(numpy.uint8(deconvolved))
When I finished the coding, 215:Assertion failed happened, and I think there is no wrong code, but I couln't solve it. How could I solve this problem?
import urllib.request as req
url = "http://uta.pw/shodou/img/28/214.png"
req.urlretrieve(url, "test.png")
import cv2
img = cv2.imread("test.png")
print(img)
%matplotlib inline
import matplotlib.pyplot as plt
import cv2
img = cv2.imread("test.jpg")
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
Error:
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-11-0f580eb5ee11> in <module>
6 import cv2
7 img = cv2.imread("test.jpg")
----> 8 plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
9 plt.show()
error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
You are getting above error because of below line:
img = cv2.imread("test.jpg")
Your image is actually a PNG file, not JPG file. So, replace above line to img = cv2.imread("test.png").
I am trying to apply cv2.createBackgroundSubtractorMOG() to this Image:
to eliminate all background brightness and only leave the two bright objects in the middle for further analysis. Is this the right approach for this task? If not, how would I do that?
import cv2
img = cv2.imread('image.png')
sharp_img = cv2.createBackgroundSubtractorMOG().apply(img)
Output:
Traceback (most recent call last):
File "/home/artur/Desktop/test.py", line 4, in <module>
sharp_img = cv2.createBackgroundSubtractorMOG().apply(img)
AttributeError: module 'cv2.cv2' has no attribute 'createBackgroundSubtractorMOG
Edit:
MOG does not seem to work.
Code:
import cv2
img = cv2.imread('image.png')
sharp_img = cv2.bgsegm.createBackgroundSubtractorMOG().apply(img)
cv2.imwrite('image2.png', sharp_img)
Output:
Traceback (most recent call last):
File "/home/artur/Desktop/test.py", line 4, in <module>
sharp_img = cv2.bgsegm.createBackgroundSubtractorMOG().apply(img)
AttributeError: module 'cv2.cv2' has no attribute 'bgsegm'
MOG2 seems to work but with no satisfying result:
Code:
import cv2
img = cv2.imread('image.png')
sharp_img = cv2.createBackgroundSubtractorMOG2().apply(img)
cv2.imwrite('image2.png', sharp_img)
Output Image:
I tried to play around with the args of the MOG2 Method from the docs but with no change.
from the docs, try this:
sharp_img = cv.bgsegm.createBackgroundSubtractorMOG().apply(img)
or
sharp_img = cv2.createBackgroundSubtractorMOG2().apply(img)
import cv2
img = cv2.imread('image.png')
max,min = img.max(),imgg.min()
print(max,min) #helps in giving thresholding values
threshold_img = cv2.threshold(blurred, 127, 255,cv2.THRESH_BINARY) #good starting point to give t1 value as half of max value of image
cv2.imshow(threshold_img)
This approach is a good starting point in your case, as you have two bright peaks that you want to separate from the noise. Once you have identified the required threshold limits, you should be able to isolate the two spots from the noise in the background. You can further use cv2.erode and cv2.dilate if needed to remove further noise.
this is the basic code from opencv-python documentation:
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('simple.jpg',0)
# Initiate STAR detector
orb = cv2.ORB()
# find the keypoints with ORB
kp = orb.detect(img,None)
# compute the descriptors with ORB
kp, des = orb.compute(img, kp)
# draw only keypoints location,not size and orientation
img2 = cv2.drawKeypoints(img,kp,color=(0,255,0), flags=0)
plt.imshow(img2),plt.show()
and it gives me this error:
Traceback (most recent call last):
File "C:\Python27\test.py", line 18, in <module>
img2 = cv2.drawKeypoints(img,kp,color=(0,255,0), flags=0)
error: ..\..\..\..\opencv\modules\features2d\src\draw.cpp:115: error: (-215) !outImage.empty() in function cv::drawKeypoints
i have to mention this error happens in opencv-PYTHON, can you help me out please? struggling really to make it work
i've found the solution
it couldn't find the image
i changed
img = cv2.imread('simple.jpg',0)
to
img = cv2.imread('c:\\python27\\sample.jpg', cv2.IMREAD_GRAYSCALE)
and it worked
note that the image i used for the sample image was one of my own grayscale images.