Quantcast
Viewing all 41027 articles
Browse latest View live

Blob Detector Not working when it should on obvious blobs, makes no sense

So I have an HSV filtered image that I am trying to do blob detection on but for some reason it is not working. The image is this one: https://i.stack.imgur.com/OhIaY.png Using the Simple Blob Detector, I get this: https://i.stack.imgur.com/07wl0.png However, on other samples such as https://i.stack.imgur.com/mYgbc.png, the code works perfectly fine and does the job I want. What parameter do I change? I'm really not sure what's going wrong, this should be working. My code is attached below: import cv2 import numpy as np from matplotlib import pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = [20, 10] img = cv2.imread('graphenetest.png') #img = cv2.resize(img,(800,600)) SLG_MIN = np.array([114, 50, 50],np.uint8) SLG_MAX = np.array([116, 255, 255],np.uint8) hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) frame_threshed = cv2.inRange(hsv_img, SLG_MIN, SLG_MAX) imagem = cv2.bitwise_not(frame_threshed) kernel = np.ones((10, 10), np.uint8) #blur = cv2.morphologyEx(imagem, cv2.MORPH_CLOSE, kernel) median = cv2.medianBlur(imagem,9) im = median plt.imshow(im) plt.title('Single Layer Graphene Detected') plt.show() # Setup SimpleBlobDetector parameters. params = cv2.SimpleBlobDetector_Params() # Change thresholds params.minThreshold = 50 params.maxThreshold = 100 # Filter by Area. params.filterByArea = True params.minArea = 10000 params.maxArea = 100000000 params.filterByCircularity = False params.filterByInertia = False params.filterByConvexity = False # Create a detector with the parameters ver = (cv2.__version__).split('.') if int(ver[0]) < 3 : detector = cv2.SimpleBlobDetector(params) else : detector = cv2.SimpleBlobDetector_create(params) # Detect blobs. keypoints = detector.detect(im) # Draw detected blobs as red circles. # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures # the size of the circle corresponds to the size of blob #im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) img2 = im.copy() for x in range(1,len(keypoints)): img2=cv2.circle(img, (np.int(keypoints[x].pt[0]),np.int(keypoints[x].pt[1])), radius=np.int(keypoints[x].size), color=(255, 0, 0), thickness=10) # Show blobs plt.imshow(img) plt.title('Single Layer Graphene Detected') plt.show() cv2.imwrite("SLG.png", img) I tried messing with the parameters, making minArea = 150 works for the one it otherwise doesn't work for, but doing that screws the other shapes. I even tried adding a constraint to the circle drawing function: if np.int(keypoints[x].size) >= 500: but that did not help either. Besides all this parameter messing seems so arbitrary, I want something more systematic. Here is the original image I am trying to do a detection on: https://imgur.com/a/UKh7Xfu EDITED TO FIX LINK - Tetragramm

I got a middle portion of laser which is captured by angled camera. How to calculate the actual length of the black portion in image attached after getting actual contour of that.

import cv2 import numpy as np from skimage import morphology, color import matplotlib.pyplot as plt from scipy.spatial import distance as dist from imutils import perspective from imutils import contours import argparse import imutils def midpoint(ptA, ptB): return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5) img = cv2.imread('F:\\Pycode\\ADAP_ANALYZER\\kk.jpg') lowerb = np.array([0, 0, 120]) upperb = np.array([200, 100, 255]) red_line = cv2.inRange(img, lowerb, upperb) red_line = cv2.GaussianBlur(red_line, (5, 5), 0) ret, red_line = cv2.threshold(red_line, 45, 255, cv2.THRESH_BINARY) red_line = cv2.dilate(red_line, None, iterations=1) kernel = np.ones((10,10),np.uint8) red_line = cv2.erode(red_line, kernel, iterations=1) cv2.imwrite("F:\\Pycode\\ADAP_ANALYZER\\yy.jpg",red_line) nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(red_line, connectivity=8) sizes = stats[1:, -1]; nb_components = nb_components - 1 min_size = 1800 img2 = np.zeros((output.shape)) for i in range(0, nb_components): if sizes[i] >= min_size: img2[output == i + 1] = 255 cv2.imwrite("F:\\Pycode\\ADAP_ANALYZER\\xx.jpg",img2) cv2.imshow('red', img2) cv2.waitKey(0) image = cv2.imread("F:\\Pycode\\ADAP_ANALYZER\\xx.jpg") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) f,thresh = cv2.threshold(gray, 70, 255, cv2.THRESH_BINARY) thresh = cv2.erode(thresh, None, iterations=1) thresh = cv2.dilate(thresh, None, iterations=1) cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) c = max(cnts, key=cv2.contourArea) for var in c: with open('c:\\your_file.txt', 'a') as f: f.write(str(var) + "\n") print(var) for contour in cnts: perimeter = cv2.arcLength(contour, True) print(perimeter/2) # determine the most extreme points along the contour extLeft = tuple(c[c[:, :, 0].argmin()][0]) extRight = tuple(c[c[:, :, 0].argmax()][0]) extTop = tuple(c[c[:, :, 1].argmin()][0]) extBot = tuple(c[c[:, :, 1].argmax()][0]) green, top-most is blue, and bottom-most is teal cv2.drawContours(image, [c], -1, (0, 255, 255), 2) cv2.imshow("Image", image) cv2.waitKey(0)

java opencv Helloworld - how?

I really am missing something. I can build opencv on my raspberry pi, and end up with opencv-XXX.jar and libopencv_javaXXX.so in /usr/local/share/OpenCV/java/ Great! I believe the so file is statically linked because i set BUILD_SHARED_LIBS=OFF in my cmake command, however, I did note in the cmake output it does say "Link libraries: Dynamic load" My Helloworld.java program looks like this: import org.opencv.core.*; class HelloWorld { static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } public static void main(String[] args) { System.out.println("hello."); } } I can compile this when I put the jar file in the classpath using "javac -cp /usr.../opencv-XXX.ar HelloWorld.java" but when I run it after (successfully) putting the .so file in the LD_LIBRARY_PATH, I get: Segmentation fault It does it with 4.1.0, 4.0.0, and 3.4.1 and is obviously something I am not doing right. Help!

after build opencv with -DBUILD_SHARED_LIBS=OFF, I still need external libraries to run apps with opencv.

I use a ubuntu 1604 python 3.6 docker image to set up the build environments. And successfully built opencv python3 with -DBUILD_SHARED_LIBS=OFF. But when I copy the cv2.cpython-36m-x86_64-linux-gnu.so file to other container base on a same image, I still need to set up environments to use this library such as libjpeg, libpng, libwebp and so on. How can I get the same result with the case directly use "pip install opencv-python"? When I use pip install opencv-python, I don't need to set up others environments any more.

Opencv C++ compilation error anonymous namespace ::hlineResize

I have Opencv 3.4.3 installed on my Raspberry Pi. When I try to compile a simple C++ script with "g++ -std=c++0x -o runnable removeRedEyes.cpp `pkg-config --libs --cflags opencv`" it throws me the error given below. Opencv built succesfully without error. What woulde be the cause? Thanks. /usr/local/lib/libopencv_imgproc.so: undefined reference to `void (anonymous namespace)::hlineResize(unsigned char*, int, int*, (anonymous namespace)::ufixedpoint16*, (anonymous namespace)::ufixedpoint16*, int, int, int)' /usr/local/lib/libopencv_imgproc.so: undefined reference to `void (anonymous namespace)::hlineResize(signed char*, int, int*, (anonymous namespace)::fixedpoint32*, (anonymous namespace)::fixedpoint32*, int, int, int)' /usr/local/lib/libopencv_imgproc.so: undefined reference to `void (anonymous namespace)::hlineResizeCn(unsigned short*, int, int*, (anonymous namespace)::ufixedpoint32*, (anonymous namespace)::ufixedpoint32*, int, int, int)' /usr/local/lib/libopencv_imgproc.so: undefined reference to `void (anonymous namespace)::hlineResizeCn(int*, int, int*, (anonymous namespace)::fixedpoint64*, (anonymous namespace)::fixedpoint64*, int, int, int)' collect2: ld returned 1 exit status

how to detect rectangle opencv js

Detect rectangle in video if detected rectangle then crop image and display using opencv js

opencv.js how to use opengl or opencl

I know that OpenCV can run OpenCL acceleration in android, then it can run opencv.js with opencl? in the browser of andorid or run opencv.js with opengl(webgl) [android run opencv on opencl](https://docs.opencv.org/3.4/d7/dbd/tutorial_android_ocl_intro.html)

Failed building "install file"

I am using c++ on eclipse, win 10. I have already generate opencv file and imported to eclipse. However, when I click project -> build project it failed on this process: [ 30%] Building CXX object modules/core/CMakeFiles/opencv_core.dir/src/directx.cpp.obj and there are 55 error, according to the log, 1st error: C:\Program Files\opencv\sources\modules\core\src\directx.cpp:1035:5: error: 'D3D11_TEXTURE2D_DESC' was not declared in this scope 55th error: C:\Program Files\opencv\sources\modules\core\src\directx.cpp:1303:19: error: 'CL_SUCCESS' was not declared in this scope if (status != CL_SUCCESS) As you can see all of them are happened in same file:C:\Program Files\opencv\sources\modules\core\src\directx.cpp So what should I do in order to fix this problem. Thank you inadvence

Horizontal projection of area between 2 circles

I use OpenCV library with python. I would like to make an horizontal projection of area between two circles. As show in image below. ![image description](/upfiles/15592240188046945.jpg)

how to solve this opencv-program

http://jwlee2218.blogspot.com/2017/11/opencv-feature-matching.html i want to make a program that searches the wally. this is a code: import bumpy as np import cv2 import matplotlib.pyplot as pat img1=cv2.imread(‘icy.jpg’,0) img2=cv2.imread(‘wally.png’,0) sift=cv2.xfeatures2d.SIFT_create() kp1,des1=sift.detectAndCompute(img1,None) kp1,des2=sift.detectAndCompute(img2,None) bf=cv2.BFMatcher() matches=bf.knnMatch(des1,des2,k=2) good=[] for m,n in matches: if m.distance<0.75*n.distance: good.append([m]) img3=cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=2) plt.imshow(img3) plt.show() But i have another errors. this is a error: syntaxerror keyword can't be an expression I don't understand what they say

Which are color blind safe palettes?

I am looking to use a color spectrum safe for color vision impaired viewers. Are there color vision impaired safe palettes on ColorMaps in OpenCV? An example palette I would like to use is found in "Color Design for the Color Vision Impaired" which you can see from, http://colororacle.org/design.html. The article shows a modified spectral color scheme, captured in a screenshott below: ![image description](/upfiles/15592425415057514.png) "The precipitation map in the first row of Figure 8, for example, shows low quantities of rainfall in red, and intermediate values in green. Hence, low and intermediate values appear identical for readers with deuteranopia. The map in the second row uses an alternative spectral ramp that omits yellow-green, uses a darker red, and places the transition between yellow and blue at the mean of all values."

Do different png compression rates result in different images?

I have some ImageNet 2012 images in JPEG. I was using two lines of simple code: imread and imwrite to convert them to png with different compression rates. However, I have noticed that: 1. If I use a low compression rate (e.g.,0), the output images will be all in the same size (while they have different sizes before processing by cv). Why this happened? 2. I know that png compression is lossless so by doing imwrite with different compression rates, I should obtain identical images (e.g., exactly the same pixel value in each pixel(i, j)). I validated this by using different image input pipelines and found it is true. However, I wonder if different compression rates can result in other different features beyond pixel values. (I doubt this since later on I was using two batches of png images which only differ in compression rates for a specific task and expecting they two could give similar results while they didn't.) Thanks.

make opencv-4.0.0 fails

[ 32%] Building CXX object modules/core/CMakeFiles/opencv_test_core.dir/test/test_intrin256.avx2.cpp.o [ 32%] Linking CXX executable ../../bin/opencv_test_core ../../lib/libopencv_imgcodecs.so.4.0.0: undefined reference to `WebPFree' collect2: error: ld returned 1 exit status modules/core/CMakeFiles/opencv_test_core.dir/build.make:659: recipe for target 'bin/opencv_test_core' failed make[2]: *** [bin/opencv_test_core] Error 1 CMakeFiles/Makefile2:1282: recipe for target 'modules/core/CMakeFiles/opencv_test_core.dir/all' failed make[1]: *** [modules/core/CMakeFiles/opencv_test_core.dir/all] Error 2 Makefile:162: recipe for target 'all' failed make: *** [all] Error 2

SimpleBlobDetector_Params() doesn't detect the blobs on the edges of the image

So I have this image of blobs below: ![image description](/upfiles/15592748492765224.png) When I ran the code below, some of the blobs on the edges of the image weren't on detected as seen on the next image. ![image description](/upfiles/15592768856612655.png) Can anyone help me with detecting the others? Thanks params = cv2.SimpleBlobDetector_Params() params.minDistBetweenBlobs = 10 params.filterByColor = True params.maxArea = 10000 params.minThreshold = 10 params.maxThreshold = 200 params.filterByArea = True params.minArea = 50 params.filterByCircularity = True params.minCircularity = 0 params.filterByConvexity = True params.minConvexity = 0 params.filterByInertia = True params.minInertiaRatio = 0.1 detector = cv2.SimpleBlobDetector(params) keypoints = detector.detect(res) im_with_keypoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) res = cv2.drawKeypoints(res, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) print("LENGTH: %d" %len(keypoints)) print(keypoints) i=0 for kp in keypoints: print("(%f,%f)"%(kp.pt[0],kp.pt[1])) i+=1 cv2.rectangle(res,(int(kp.pt[0]),int(kp.pt[1])),(int(kp.pt[0])+1,int(kp.pt[1])+1),(0,255,0),3) print("LEN: %d" %i) cv2.imshow("Keypoints", im_with_keypoints) cv2.imshow("RES", res) cv2.waitKey(0)

Detect blur and overlapping image

I have a huge repository of images. From this repository I have to remove blur images (underlit and over lit) and also images that are superimposed or overlapped. Please help me or let me know any algorithm to solve the problem.

cbuilder integration

has anyone managed to use opencv with cbuilder (10.2 onwards) ?

Ignore part of an image whilst detecting LED colour

I have a board with five small LEDs that switch between red or green randomly. A few centimeters above each led, there are large button like switches that manually switch the colour of LED. These Buttons are either Red or Green in colour. I want to use my portable webcam to detect when an LED goes red and know which one it is (MAP it), and make a decision from that. How do you I ignore the Red/Green Buttons, as I only want to detect when the LED goes Red. Also, how can I map the LEDs relative to the board. I'm a total newbie to CV. Would love some guidance.

How to detect clock drawing

How can a hand drawn clock be analyzed to see whether or not it was drawn correctly? Some examples of why it would be drawn incorrectly are the numbers being in the wrong locations, the circle not enclosing the numbers and the numbers not existing.

why do I get "random" window size with resizeWindow()?

I'm using Ubuntu 18.04 with Eclipse C++/CUDA toolchain. I built OpenCV using 4.1.0 into world410. I have these lines in my program: namedWindow(g_capturedwindow, WINDOW_NORMAL | WINDOW_KEEPRATIO); resizeWindow(g_capturedwindow, 1920, 1300); // 220 extra height for toolbars moveWindow(g_capturedwindow, 1910, 0); createTrackbar("Record", g_capturedwindow, &recordseconds, 100, CallbackForRecordTrackBar); createTrackbar("Output", g_capturedwindow, &outsel, 3, CallbackForOutputTrackBar); createTrackbar("Control", g_capturedwindow, &control, 100, CallbackForControlTrackBar); setMouseCallback(g_capturedwindow, MouseCallBackFunc, 0); Everything works (no errors), and in the past my window usually comes up the correct size but lately it's been coming up very tiny, so that I need to drag the corner to make it the correct size (I want one screen pixel = one captured pixel). Whether it comes up tiny or 1:1 scale seems to change between compilations without any changes to this code. I like the ability to have it automatically scale up when I expand the window to full screen mode, which is does. I have a 4K computer screen. If I change it to WINDOW_AUTOSIZE then it doesn't enlarge the captured image to fill the expanded window. Is there a proper set of parameters I should use for resizeWindow(), or is there a better function, so that it always comes up first time with 1:1 scaling as the default yet allows me to drag the window corner to resize the image while maintaining the aspect ratio? And does anyone know what would cause it to start with a tiny window when I clearly am making it 1920x1300?

Opencv Email Notification

Hello, I've run into a road block in my opencv motion detection script while trying to adapt an "import smtplib" into my loop. I did not create the original script so I can't take any credit for that. The problem I'm having is, when I run the script as is, and movement is detected it sends me an email for every frame that detected motion - it sends me a BUNCH of emails. How can I change the script so it only sends me (1) email every 60 seconds once movement was detected (and doesn't have a bunch of emails waiting to send in the background) and the loop function continues without interruption? ---------- # import the necessary packages from __future__ import print_function from pyimagesearch.basicmotiondetector import BasicMotionDetector from imutils.video import VideoStream import numpy as np import datetime import imutils import time import cv2 # initialize the video streams and allow them to warmup print("[INFO] starting cameras...") webcam1 = VideoStream(src=0).start() webcam2 = VideoStream(src=4).start()#src 0,2,4 work time.sleep(2.0) # initialize the two motion detectors, along with the total # number of frames read camMotion1 = BasicMotionDetector() camMotion2 = BasicMotionDetector() total = 0 # loop over frames from the video streams while True: # initialize the list of frames that have been processed frames = [] # loop over the frames and their respective motion detectors for (stream, motion) in zip((webcam1, webcam2), (camMotion1, camMotion2)): # read the next frame from the video stream and resize # it to have a maximum width of 400 pixels frame = stream.read() frame = imutils.resize(frame, width=400) # convert the frame to grayscale, blur it slightly, update # the motion detector gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (21, 21), 0) locs = motion.update(gray) # we should allow the motion detector to "run" for a bit # and accumulate a set of frames to form a nice average if total < 32: frames.append(frame) continue # otherwise, check to see if motion was detected if len(locs) > 0: # initialize the minimum and maximum (x, y)-coordinates, # respectively (minX, minY) = (np.inf, np.inf) (maxX, maxY) = (-np.inf, -np.inf) # loop over the locations of motion and accumulate the # minimum and maximum locations of the bounding boxes for l in locs: (x, y, w, h) = cv2.boundingRect(l) (minX, maxX) = (min(minX, x), max(maxX, x + w)) (minY, maxY) = (min(minY, y), max(maxY, y + h)) # draw the bounding box cv2.rectangle(fram e, (minX, minY), (maxX, maxY), (0, 0, 255), 3) import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("my_email", "my_password") msg = "INTRUDER!" server.sendmail("my_email", "email_to_send_to", msg) server.quit() # update the frames list frames.append(frame) # increment the total number of frames read and grab the # current timestamp total += 1 timestamp = datetime.datetime.now() ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p") # loop over the frames a second time for (frame, name) in zip(frames, ("Webcam1", "Webacm2")): # draw the timestamp on the frame and display it cv2.putText(frame, ts, (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1) cv2.imshow(name, frame) # check to see if a key was pressed key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): break # do a bit of cleanup print("[INFO] cleaning up...") cv2.destroyAllWindows() webcam1.stop() webcam2.stop() ----------
Viewing all 41027 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>