FitEllipse opencv-python > 4 - python-3.x
I'm having a quite big issue with fitellipse and opencv-python.
I know that I have to install opencv-contrib-python to get some functions but it doesn't work with fitellips function.
when using :
import cv2
cv2.fitEllipse()
here is the result:
TypeError: fitEllipse() missing required argument 'points' (pos 1)
but if now I try it using, for example, contour detection from an image:
img = cv2.imread('messi5.jpg',0)
retz,bawgray=cv2.threshold(img , 110,255,cv2.THRESH_BINARY)
contours,hierarchy = cv2.findContours(bawgray,1,1)
cnt = contours
big_contour = []
maxop = 0
for i in cnt:
areas = cv2.contourArea(i)
if areas > maxop:
maxop = areas
big_contour = i
img=cv2.drawContours(img, big_contour, -1, (0,255,0), 3)
cv2.FitEllipse(big_contour)
here is the result:
AttributeError: module 'cv2.cv2' has no attribute 'FitEllipse'
I use opencv-python 4.2.0.34
and opencv-contrib-python 4.2.0.34
You have not provided output for cv2.fitEllipse. Also you have misspelled the name. It is "fitEllipse" not "FitEllipse" with lower case "f".
Try
result = img.copy()
((centx,centy), (width,height), angle) = cv2.fitEllipse(big_contour)
cv2.ellipse(result, (int(centx),int(centy)), (int(width2/),int(height2/)), angle, 0, 360, (0,0,255), 1)
Related
How to create a custom colormap lut for opencv or is it posible to put together to colormaps from opencv? [duplicate]
I created a custom colormap in a text file, read from the python 3.6. To map each color in for loop it takes approx. 9 seconds. Here is the snippet: for x in range(256): # z = int(rgb_c[x][0]) # r = int(rgb_c[x][1]) # g = int(rgb_c[x][2]) # b = int(rgb_c[x][3]) # Apply color to ndvi # ndvi_col[ndvi_g == z[x]] = [r[x], g[x], b[x]] ndvi_col[ndvi_g == int(rgb_c[x][0])] = [int(rgb_c[x][1]), int(rgb_c[x][2]), int(rgb_c[x][3])] Heard about pypy jit compiler can increase speed and performance, will this impact on for loop? I even tried a separate list but nothing changed. I am open for any suggestions to improve speed and performance.
Posted solution in case. Original code in github. #!/usr/bin/env python ''' OpenCV Custom Colormap Example Copyright 2015 by Satya Mallick <spmallick#learnopencv.com> ''' import cv2 import numpy as np def applyCustomColorMap(im_gray) : lut = np.zeros((256, 1, 3), dtype=np.uint8) #Red lut[:, 0, 0] = [255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,253,251,249,247,245,242,241,238,237,235,233,231,229,227,225,223,221,219,217,215,213,211,209,207,205,203,201,199,197,195,193,191,189,187,185,183,181,179,177,175,173,171,169,167,165,163,161,159,157,155,153,151,149,147,145,143,141,138,136,134,132,131,129,126,125,122,121,118,116,115,113,111,109,107,105,102,100,98,97,94,93,91,89,87,84,83,81,79,77,75,73,70,68,66,64,63,61,59,57,54,52,51,49,47,44,42,40,39,37,34,33,31,29,27,25,22,20,18,17,14,13,11,9,6,4,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] #Green lut[:, 0, 1] = [ 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,252,250,248,246,244,242,240,238,236,234,232,230,228,226,224,222,220,218,216,214,212,210,208,206,204,202,200,198,196,194,192,190,188,186,184,182,180,178,176,174,171,169,167,165,163,161,159,157,155,153,151,149,147,145,143,141,139,137,135,133,131,129,127,125,123,121,119,117,115,113,111,109,107,105,103,101,99,97,95,93,91,89,87,85,83,82,80,78,76,74,72,70,68,66,64,62,60,58,56,54,52,50,48,46,44,42,40,38,36,34,32,30,28,26,24,22,20,18,16,14,12,10,8,6,4,2,0 ] #Blue lut[:, 0, 2] = [195,194,193,191,190,189,188,187,186,185,184,183,182,181,179,178,177,176,175,174,173,172,171,170,169,167,166,165,164,163,162,161,160,159,158,157,155,154,153,152,151,150,149,148,147,146,145,143,142,141,140,139,138,137,136,135,134,133,131,130,129,128,127,126,125,125,125,125,125,125,125,125,125,125,125,125,125,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126] #Apply custom colormap through LUT im_color = cv2.LUT(im_gray, lut) return im_color; if __name__ == '__main__' : im = cv2.imread("pluto.jpg", cv2.IMREAD_GRAYSCALE); im = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR); im_color = applyCustomColorMap(im); cv2.imwrite('/tmp/colormap_algae.jpg', im_color) cv2.imshow("Pseudo Colored Image", im_color); cv2.waitKey(0);
Python - OpenCv - Gradient computing
I've download the opencv from https://opencv.org/opencv-demonstrator-gui/ to make some live test on some images. I found that this filter work perfectly for my needs: , I need to code it in my python script, tried to follow this tutorial :https://docs.opencv.org/3.4/d2/d2c/tutorial_sobel_derivatives.html but I'm unable to find and match setting I need (pre-filtering Deriche, or Schar operator type). I guess also I should use this syntax: cv.Sobel(gray, ddepth, 1, 0, ksize=3, scale=scale, delta=delta, borderType=cv.BORDER_DEFAULT) Thx. UPDATE Using this lines I'm close to right result: scale = 1 delta = 0 ddepth = cv2.CV_16S src = cv2.imread(image, cv2.IMREAD_COLOR) src = cv2.GaussianBlur(src, (3, 3), 0) gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) grad_x = cv2.Sobel(gray, ddepth, 1, 0, ksize=3, scale=scale, delta=delta, borderType=cv2.BORDER_DEFAULT) # Gradient-Y # grad_y = cv.Scharr(gray,ddepth,0,1) grad_y = cv2.Sobel(gray, ddepth, 0, 1, ksize=3, scale=scale, delta=delta, borderType=cv2.BORDER_DEFAULT) abs_grad_x = cv2.convertScaleAbs(grad_x) abs_grad_y = cv2.convertScaleAbs(grad_y) grad = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)
You are only doing the X derivative Sobel filter in Python/OpenCV. It is likely you really want the gradient magnitude, not the X directional derivative. To compute the magnitude, you need both the X and Y derivatives and then compute the magnitude. You also like will need to compute as float so as not to get one sided derivatives. You can later convert the magnitude to 8-bit if you want. gradx = cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=3) grady = cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=3) gradmag = cv2.magnitude(gradx,grady) The Scharr is similar and can be found at https://docs.opencv.org/master/d4/d86/group__imgproc__filter.html#gaa13106761eedf14798f37aa2d60404c9
How to fix "TypeError: Expected Ptr<cv::UMat> for argument '%s'"
I'm writing codes to accelerate my program using CUDA, but I got a tricky error. I have no idea about it.My environment is OpenCV 4.1.1, python 3.6. Here is my code. I define a function to rotate the img, def rotate(img, angle): ''' ''' if len(img.shape) == 3: (rows, cols, channels) = img.shape out_size = (cols, rows, channels) else: (rows, cols) = img.shape out_size = (cols, rows) if angle == 0: dst = img else: # img_gpu = cv2.cuda_GpuMat() img_gpu = cv2.cuda_GpuMat() out_gpu = cv2.cuda_GpuMat() # M_gpu = cv2.cuda_GpuMat() # out_size_gpu = cv2.cuda_GpuMat() # border_value_gpu = cv2.cuda_GpuMat() m = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1) img_gpu.upload(img) # M_gpu.upload(M) # out_size_gpu.upload((12000, 6000)) # border_value_gpu.upload((0, 0, 0)) cols_gpu = cv2.cuda_GpuMat() rows_gpu = cv2.cuda_GpuMat() cols_gpu.upload(cols) rows_gpu.upload(rows) print(type(img)) print(img.shape) (row,col) = img.shape print([img_gpu.size()[0],img_gpu.size()[1]]) # M = np.float32([[1,0,100],[0,1,50]]) # out=cv2.UMat(out_gpu,(284,284)) out_gpu = cv2.cuda.warpAffine(img_gpu, m, (col,row)) dst = out_gpu.download() return dst then I call it. img = cv2.imread('../FengZhan/temp.png',0) img_rotate = rotate(img, -10) it cannot work and has the following error: <ipython-input-48-41cd06952793> in rotate(img, angle) 36 # M = np.float32([[1,0,100],[0,1,50]]) 37 # out=cv2.UMat(out_gpu,(284,284)) ---> 38 out_gpu = cv2.cuda.warpAffine(img_gpu, m, (col,row)) 39 40 dst = out_gpu.download() TypeError: Expected Ptr<cv::UMat> for argument '%s' I tried to replace img_gpu with cv2.UMat(img_gpu), but it still cannot work. Anybody help me?
I got this error: TypeError: Expected Ptr<cv::UMat> for argument '%s' code: image = cv2.imread("image_path") image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY) Simply because the image path was incorrect and I was loading an image which wasn't there. I realize it might not be your case however I hope it may help others who encounter this error.
I don't understand why do you define in the beginning out_gpu = cv2.cuda_GpuMat(). And in the end you set it again to: out_gpu = cv2.cuda.warpAffine(img_gpu, m, (col,row)). The reason why you get this error may be because of your code out_gpu = cv2.cuda.warpAffine(img_gpu, m, (col,row)) argument img_gpu is supposed to be a string link to an image, yet it is defined previously as img_gpu = cv2.cuda_GpuMat(). Try to correct this by replacing the line img_gpu.upload(img) by uploaded_img = img_gpu.upload(img)
Change your image to be numpy array np.array(image)
It seems to be one bug for OpenCV as I issued at OpenCV cuda bindings for python seem receive wrong param types for cudawarping/src/warp.cpp #2393. However, even I fix this bug the speed is not satisying (slower than CPU version), if there are some other tricks, maybe we can share with each other. Good Luck.
Remove unwanted text in logo detection- Image Processing, Computer vision
I am trying to detect logo in invoices. Though I am able to get some results but not sufficient enough to process. While detecting logos, Unwanted text is also getting detected. The following is from actual invoice:-original Image and the following results I am getting Image after operations I am using the`following code which I have written:- gray=cv2.imread("Image",0) ret,thresh1 = cv2.threshold(gray,180,255,cv2.THRESH_BINARY) kernel_logo = np.ones((10,10),np.uint8) closing_logo = cv2.morphologyEx(thresh1,cv2.MORPH_CLOSE,kernel_logo, iterations = 1) n=3 noise_removed_logo = cv2.medianBlur(closing_logo, n) eroded_logo = cv2.erode(noise_removed_logo,kernel_logo, iterations = 8) dilated_logo=cv2.dilate(eroded_logo,kernel_logo, iterations=3) Could you please help me what changes should I make to remove noise from my documented image. I am new to Computer Vision Few more sample:- Original document The result I am getting:- Result after operations on document
Hello Mohd Anas Khan . Your approch to define logo is too simple so it couldn't work. If you want a product-level approach, use some machine learning or deep learning. If you want just some toys, then a simple countours finder with fixed rules should work. For example, in the following approach i defined "logo" as "the contour which has biggest area". You'll need more rules later, so good luck. import numpy as np import cv2 im = cv2.imread('contours_1.jpg') imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,127,255, cv2.THRESH_BINARY_INV) rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) threshed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, rect_kernel) cv2.imwrite("contours_1_thres.jpg", threshed) im2, contours, hierarchy = cv2.findContours(threshed,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) ws = [] hs = [] areas = [] for contour in contours: area = cv2.contourArea(contour) x, y, w, h = cv2.boundingRect(contour) print("w: {}, h: {}, area: {}".format(w, h, area)) ws.append(w) hs.append(h) areas.append(area) max_idx = np.argmax(areas) cv2.drawContours(im, [contours[max_idx]], -1, (0, 255, 0), 3) # cv2.drawContours(im, contours, -1, (0, 255, 0), 3) cv2.imwrite("contours_1_test.jpg", im) The output images are as follow : (The detected logo is covered in green box )
How to show text in image using pillow
I recently started to learn how to work with Pillow in python and this is what i have so far (code below). If i run this i get the following error: ValueError: cannot determine region size; use 4-item box i've tried removing the base.paste line, this removes the error but doesn't show any text. i hope someone here could help me to fix this so the text is showing in the image. #app.route("/imgtest/") def imgtest(): f_text = textwrap.fill(request.args.get('text'), 10) base = Image.open(config.assetsfolder+'/'+'facts.bmp').convert("RGBA") txtO = Image.new("RGBA", base.size, (255, 255, 255, 0)) font = ImageFont.truetype(config.assetsfolder+'/'+'fonts'+'/'+'Roboto-Bold.ttf', 15) canv = ImageDraw.Draw(txtO) canv.text((95, 283), f_text, font=font, fill="Black") base.paste(f_text) base.save(config.assetsfolder+'/'+'done'+'/'+'boop.png') return send_file(config.assetsfolder+'/'+'done'+'/'+'boop.png')``` How do i show the text in the image?
If you are using pillow 4.0, I believe this would be an issue with the pillow version. Try in your cmd the following: pip uninstall pillow pip install Pillow==3.4.2
Played a bit around by adding some random code and reading the docs a bit better #app.route("/fact/") def fact(): filename=(config.assetsfolder+'/'+'facts.bmp') args=request.args.get('text') font = ImageFont.truetype(config.assetsfolder+'/'+'fonts'+'/'+'Roboto-Bold.ttf', size=20) text = wrap(font, args, 340) im = Image.open(filename) text_layer = Image.new('RGBA', im.size) d = ImageDraw.Draw(text_layer) location = (90, 600) text_color = (20, 20, 20) d.text(location, text, font=font, fill=text_color) text_layer = text_layer.rotate(-13, resample=Image.BICUBIC) im.paste(text_layer, (0, 0), text_layer) im.save(config.assetsfolder+'/'+'done'+'/'+'fact.png') return send_file(config.assetsfolder+'/'+'done'+'/'+'fact.png') This did the job for me.