Hi,
I've tried to use kmeans function, but something is not clear to me.
Lets say that I have an array of points
and I want to center all of them to four points :
topLeft, topRight, bottomeft, bottomRight.
How I can achieve it ?
I tried to make it work, but failed to understand (for now)..
also,
It's very hard to understand what is happening on the Mat's..
No option to print/see the actual Mat on some console / or in deug mode ?
Thank's !!
the code:
public void colorMask(View view)
{
//Image Input :
Bitmap one =
drawableToBitmap(getResources().getDrawable(R.drawable.dsc_1304_cutted_bigger, this.getTheme()));
Mat img1 = new Mat();
Utils.bitmapToMat(one, img1, true);// moving one to img1 Mat structure.
// downsize the image.
Mat pyrDowntmp = new Mat();
Imgproc.resize(img1, pyrDowntmp, new Size(img1.cols() / 4, img1.rows() / 4));
img1.release();
Mat pyrDown = new Mat();
cvtColor(pyrDowntmp, pyrDown, COLOR_RGBA2RGB);
pyrDowntmp.release();
List intersections1 = new ArrayList<>();
org.opencv.core.Point pointsArray[] = new org.opencv.core.Point[ intersections1.size() ];
intersections1.toArray(pointsArray);
Mat intersections = new Mat();
Mat intersections32f = new Mat();
// draw all the intersections. (see it ok)
for (Point point: pointsArray)
{
// draw on the actual image:
circle(pyrDown, point, 5, new Scalar(255, 0, 0), 2);//Red
// want to draw it on a Mat that will be given to kmeans as data mat.
// tried to draw on a mat:
circle(intersections, point, 5, new Scalar(255, 0, 0), 2);
// tried to 'put' on 32f Mat.
//(the first two parameters - issue an error.('need double')
intersections32f.put(point.x, point.y, 1.0);
}
intersections.convertTo(intersections32f, CvType.CV_32F);
// want to find the 4 corners of the points..
Mat labels = Mat.zeros(intersections32f.rows(), intersections32f.cols(), CvType.CV_32F);
labels.put(0, 0, 1.0); // topLeft
labels.put(0, labels.rows() - 1, 1); // bottomLeft
labels.put(labels.cols() - 1, 0, 1); // topRight
labels.put(labels.rows() - 1, labels.cols() - 1, 1); // bottomRight
TermCriteria criteria = new TermCriteria(TermCriteria.COUNT, 100, 1);
int attempts = 50;
int flags = Core.KMEANS_PP_CENTERS;
Mat centers = new Mat();
double res = kmeans(intersections32f, 4, labels, criteria, attempts, flags, centers);
Bitmap imageMatched = Bitmap.createBitmap(centers.cols(), centers.rows(), Bitmap.Config.RGB_565);
Utils.matToBitmap(centers, imageMatched);
imageViewMy.setImageBitmap(imageMatched);
/*
public static double kmeans(@NotNull Mat data,
int K,
@NotNull Mat bestLabels,
@NotNull TermCriteria criteria,
int attempts,
int flags)
*/
}
↧
kmeans in Android (Java)-
↧
Recording Video of an Event
Hello,
I am a test engineer and I am performing a continuous test on a product. I am reading a parameter of the product from a sensor and when that parameter is within a certain range the test fails.
It test has been failing only at night when no one is around.
I want to setup a camera to record the failure event. I would like to use some kind of USB camera and continuously record video and save video ONLY when the event occurs. In other words, save the video 5 seconds before the event until 5 seconds after the event.
I want to create a Python script to do this. Is are there any tutorials for how accomplish this? Thank you!
Currently for the test, I am using a programming language called LabVIEW to automate the test. My plan is to create this video recording python script and then use LabVIEW to call this script.
↧
↧
Do I need to calculate hist at prediction time in SVM?
I am training my dataset with the below code:
for file in glob.glob('C:\*.png'):
image = cv2.imread(file, 1)
image = cv2.resize(img, (60, 120))
hog = cv2.HOGDescriptor((60,120), (8,8), (4,4), (4,4), 9)
hist = hog.compute(image)
samples.append(hist)
labels.append(-1)
I am using `hist = hog.compute(image)`. This code is in the training part, but when I do the prediction part:
hog = cv2.HOGDescriptor((60,120), (8,8), (4,4), (4,4), 9)
svm = cv2.ml.SVM_load('svm_data.xml')
sv = svm.getSupportVectors()
rho, alpha, svidx = svm.getDecisionFunction(0)
svm_new = np.append(sv, -rho)
hog.setSVMDetector(svm_new)
I am not using `hist = hog.compute(image)`, and my results are not as good. Do I need to use hog.compute in prediction part while using `Multiscale`?
found, w = hog.detectMultiScale(img,hitThreshold=0,winStride=(8,8),padding=(16,16), scale=1.05, finalThreshold = 2.0,useMeanshiftGrouping=False)
When I try to use it, it gives an error, and without it, I am not getting good results. Am I doing wrong in the training part or in the prediction part?
↧
I can not install ArUco globally
Ubuntu 19.04. I have installed OpenCV 4.1.1 like this
https://github.com/milq/milq/blob/master/scripts/bash/install-opencv.sh
But, when I install ArUco via cmake, the following happens

Help!!!
↧
CvException
Caused by: CvException [org.opencv.core.CvException: cv::Exception: OpenCV(3.4.6) C:\build\3_4_winpack-bindings-win64-vc14-static\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor']
at org.opencv.imgproc.Imgproc.cvtColor_1(Native Method)
at org.opencv.imgproc.Imgproc.cvtColor(Imgproc.java:2347)
↧
↧
copyTo don't work
I want to make app which swap faces in picture. The mat of the picture is picMat, and I want to copy a mat of detected face on picmat, but the function copyTo don't work.
here is the code:
Bitmap faceBitmap;
SparseArray faces = faceDetector.detect(frame);
for(int i=0; i
↧
installed Opencv 4 from source, C++ headers not linked correctly
I jusst installed Opencv 4.1.1 from source, with python 3 bindings. My Python installation seems to work correctly, because if I run:
import cv2
cv2.__version__
I get '4.1.1'
However, I also want to use some C++ code. I had a previous installation of 3.4.3 that I built from source, and unfortunately I had deleted the build folder before uninstalling it. So, when I run this C++ code:
#include
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
//print opencv version
printf("opencv version: %d.%d.%d\n",CV_VERSION_MAJOR,CV_VERSION_MINOR,CV_VERSION_REVISION);
return 0;
}
When i compile with this command :
g++ -o get_version get_version.cpp -I/usr/local/include/opencv4/opencv2 -Lusr/local/lib -lopencv_core
It returned 3.4.3.
So, I wanted to fix this, so I found the old header files, and deleted them all (they were located in /usr/local/include/opencv2). But now when I try to compile my code, it gives me the error:
In file included from get_version.cpp:1:0:
/usr/local/include/opencv4/opencv2/core.hpp:52:10: fatal error: opencv2/core/cvdef.h: No such file or directory
#include "opencv2/core/cvdef.h"
^~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
But, if I navigate to /usr/local/include/opencv4/opencv2/core/, I can see the file, cvdef.h, so I don't know why the compiler can't find it.
So, why are my headers not linking correctly? And how can I fix this. I'm used to Python, so I'm I'm not used to having to deal with linking all these header files, so sorry if it's something obvious.
↧
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:

"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."
↧
How to make transparent background While Stitching using homography
I have 2 images, I want to stitch them using homography.
But I want there won't be any black border in the result image.
So I should use transparency. Do I need a create transparent background/mask? What I should do?
Example Stitched images:

But I want to make transparent the black borders
This black borders:

How can I change my code?
My code:
cv::Mat stitch(const cv::Mat &img1,const cv::Mat &img2, cv::Mat &mask, const cv::Mat &H)
{
//Coordinates of the 4 corners of the image
std::vector corners(4);
corners[0] = cv::Point2f(0, 0);
corners[1] = cv::Point2f(0, img2.rows);
corners[2] = cv::Point2f(img2.cols, 0);
corners[3] = cv::Point2f(img2.cols, img2.rows);
std::vector cornersTransform(4);
cv::perspectiveTransform(corners, cornersTransform, H);
double offsetX = 0.0;
double offsetY = 0.0;
//Get max offset outside of the image
for (size_t i = 0; i < 4; i++)
{
std::cout << "cornersTransform[" << i << "]=" << cornersTransform[i] << std::endl;
if (cornersTransform[i].x < offsetX)
{
offsetX = cornersTransform[i].x;
}
if (cornersTransform[i].y < offsetY)
{
offsetY = cornersTransform[i].y;
}
}
offsetX = -offsetX;
offsetY = -offsetY;
std::cout << "offsetX=" << offsetX << " ; offsetY=" << offsetY << std::endl;
//Get max width and height for the new size of the panorama
double maxX = std::max((double)img1.cols + offsetX, (double)std::max(cornersTransform[2].x, cornersTransform[3].x) + offsetX);
double maxY = std::max((double)img1.rows + offsetY, (double)std::max(cornersTransform[1].y, cornersTransform[3].y) + offsetY);
std::cout << "maxX=" << maxX << " ; maxY=" << maxY << std::endl;
cv::Size size_warp(maxX, maxY);
cv::Mat panorama(size_warp, CV_8UC3);
//Create the transformation matrix to be able to have all the pixels
cv::Mat H2 = cv::Mat::eye(3, 3, CV_64F);
H2.at(0, 2) = offsetX;
H2.at(1, 2) = offsetY;
cv::warpPerspective(img2, panorama, H2*H, size_warp);
//ROI for img1
cv::Rect img1_rect(offsetX, offsetY, img1.cols, img1.rows);
cv::Mat half;
//First iteration
if (mask.empty())
{
//Copy img1 in the panorama using the ROI
cv::Mat half = cv::Mat(panorama, img1_rect);
img1.copyTo(half);
//Create the new mask matrix for the panorama
mask = cv::Mat::ones(img2.size(), CV_8U) * 255;
cv::warpPerspective(mask, mask, H2*H, size_warp);
cv::rectangle(mask, img1_rect, cv::Scalar(255), -1);
}
else
{
//Create an image with the final size to paste img1
cv::Mat maskTmp = cv::Mat::zeros(size_warp, img1.type());
half = cv::Mat(maskTmp, img1_rect);
img1.copyTo(half);
//Copy img1 into panorama using a mask
cv::Mat maskTmp2 = cv::Mat::zeros(size_warp, CV_8U);
half = cv::Mat(maskTmp2, img1_rect);
mask.copyTo(half);
maskTmp.copyTo(panorama, maskTmp2);
//Create a mask for the warped part
maskTmp = cv::Mat::ones(img2.size(), CV_8U) * 255;
cv::warpPerspective(maskTmp, maskTmp, H2*H, size_warp);
maskTmp2 = cv::Mat::zeros(size_warp, CV_8U);
half = cv::Mat(maskTmp2, img1_rect);
//Copy the old mask in maskTmp2
mask.copyTo(half);
//Merge the old mask with the new one
maskTmp += maskTmp2;
maskTmp.copyTo(mask);
}
return panorama;
}
↧
↧
How to use CV_FOURCC in version 4.1.0?
Hi,
i am new with openCV. i'm trying to paste a code snippet from old versions. But i get lots of error.
VideoWriter parlakVideo("videoParlak.avi", CV_FOURCC(‘M’, ‘P’, ‘4’, ‘2’), 20, boyut, true);
VideoWriter karanlikVideo("videoKaranlik.avi", CV_FOURCC(‘M’, ‘P’, ‘4’, ‘2’), 20, boyut, true);
here is my try:
VideoWriter parlakVideo("video.wmv", VideoWriter::fourcc ((‘M’, ‘P’, ‘4’, ‘2’), 20, boyut, true);
VideoWriter karanlikVideo("video.wmv", VideoWriter::fourcc((‘M’, ‘P’, ‘4’, ‘2’), 20, boyut, true);
↧
Using OpenCV in Windows 10 with Visual Studio Code
I'm having a nightmare trying to get OpenCV to work. I've installed it with no issues, but when I try running an example code it can't find the include files. I'm using Visual Studio Code (different from Visual Studios), but all the tutorials for setting it up are for Visual Studios. I don't know whether that's what's causing the problem.
I've tried installing it in two ways, first with the pre-built libraries, and then with git-bash and cmake as described here: https://docs.opencv.org/master/d3/d52/tutorial_windows_install.html. VScode can't see the include files for either. I have tried adding the directory to the "opencv2" directory to the Path environment variable, and also to the VScode includePath.
Is there a better way of installing it that isn't specific to VS? I only need the C++ bits, if that's any easier. Also, if anyone knows how to configure VScode properly that would be helpful.
(I can't get Visual studios because I don't have enough space on my hard drive, and I can't replace the hard drive.)
↧
identifying multiple leds
Hello
I want to write a program to check the presence of multiple objects, for example leds, of different classes (like led colors) in an rigid environment, for example on an PCB, when the camera position is not fixed.
Let's say for example, that we have 30 red leds, 20 green leds and 10 blue leds which have to be checked. I can find the leds with simpleBlobDetector, and also determine their class (red, green or blue). As a result I have an unordered list of about 60 leds, with coordinates and class. But how can I match this against the ordered list of 60 reference leds?
I hope for something like findHomography, which returns a geometric transformation matrix and a list of matches.
But as far as I know, findHomography takes two ordered lists of coordinates, assuming that each keypoint is unique. But this is not always the case for technical images that may contain many instances of the same object.
↧
Mask and image
Hi all ! I have an image in true colors and a mask black and white, I want to make an image which white pixels of the mask become red in the result image and the black pixels of the mask become true colors pixels of the true colors image in the result image.
I want in in OPENCV/Python please.
Thank you
Bye
↧
↧
Any functions like numpy.polyfit in OpenCV?
i am trying to implement or kinda of 'porting' a Udacity Advanced LaneDetection project in C++ code
this project has been originally implemented in Python but i would like to implement in C++
everything was fine except Numpy.polyfit method.
Is there any function like Numpy.polyfit in opencv ? or c+++?
↧
Gpu memory leak when resizing asynchronously
I'm facing some problem with gpu resize using opencv. Here is my code:
#define MX 500
#define ASYNC 0
class job {
public:
cv::cuda::GpuMat gpuImage;
cv::cuda::Stream stream;
cv::Mat cpuImage;
~job() {
printf("job deleted\n");
}
};
void onComplete(int status, void* uData) {
job* _job = (job*) uData;
delete _job;
}
void resize(job* _job, vector buffer) {
_job->cpuImage = cv::imdecode(buffer, cv::IMREAD_COLOR);
if (ASYNC) {
_job->gpuImage.upload(_job->cpuImage, _job->stream);
cv::cuda::resize(_job->gpuImage, _job->gpuImage, cv::Size(100, 100), 0, 0, cv::INTER_NEAREST, _job->stream);
_job->gpuImage.download(_job->cpuImage, _job->stream);
_job->stream.enqueueHostCallback(onComplete, _job);
// _job->stream.waitForCompletion();
} else {
_job->gpuImage.upload(_job->cpuImage);
cv::cuda::resize(_job->gpuImage, _job->gpuImage, cv::Size(100, 100), 0, 0, cv::INTER_NEAREST);
_job->gpuImage.download(_job->cpuImage);
delete _job;
}
}
vector readFile(string filename) {
std::ifstream input(filename, std::ios::binary);
std::vector buffer(std::istreambuf_iterator(input),{});
return buffer;
}
int main() {
for (int i = 0; i < MX; i++) {
vector buf = readFile("input.jpg");
job* _job = new job();
resize(_job, buf);
printFreeGPUMemory();
}
while (true) {
// wait
}
return 0;
}
When I run resize synchronously (ASYNC = 0), the code works perfectly fine. But when I run it asynchronously (ASYNC = 1), it seems that some gpu memory is lost somewhere despite the fact that I have deleted all created GpuMats and Streams. The more loop I run, the less free memory I have. is there a bug or part of my code is wrong?
↧
Difficulty building OpenCV with MinGW
I'm trying to build OpenCV 4.1.1 with MinGW32 from the source (in Windows 10 and for C++). I've been following the instructions at the bottom of this page: https://docs.opencv.org/master/d3/d52/tutorial_windows_install.html and at the top of this page: http://eyalarubas.com/opencv-installation-on-windows-netbeans-mingw.html. So far I've successfully cloned the source, but when I press "configure" in CMake I get several errors:

The only option I changed was to enable "ENABLE_SOLUTION_FOLDERS" as instructed in the first link. CMake still allowed me to continue and "generate", however then when I typed "mingw32-make" into the command prompt it gave me more significant errors at about 20%:

I then disabled openexr and tried again, but it didn't get much further:

I don't know whether they are to do with the warnings I was getting in CMake, or whether it's something else. What should I do now?
↧
Segmentation fault while using createTrackBar in OpenCV-Python
I am using OpenCV 4.1.1.
When I try to run the trackbar tutorial code, I get the segmentation fault (core dumped) error.
It seems that the crash occurs when the trackbar is created in an existing window initialized by cv2.namedWindow() and does not occur when the 2nd argument of cv2.createTrackbar(window name) is a name of a non-existent window.
Is it a bug with the latest release or is there some fault in my installation?
I am on Ubuntu 19.04 and am using Python 3.7 and the tkinter GUI library.
import numpy as np
import cv2 as cv
def fun(x):
pass
img = np.zeros((300,512,3), np.uint8)
cv.namedWindow('image')
cv.createTrackbar('R','image',0,255,fun)
cv.createTrackbar('G','image',0,255,fun)
cv.createTrackbar('B','image',0,255,fun)
switch = '0 : OFF \n1 : ON'
cv.createTrackbar(switch, 'image',0,1,fun)
while(1):
cv.imshow('image',img)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
r = cv.getTrackbarPos('R','image')
g = cv.getTrackbarPos('G','image')
b = cv.getTrackbarPos('B','image')
s = cv.getTrackbarPos(switch,'image')
if s == 0:
img[:] = 0
else:
img[:] = [b,g,r]
cv.destroyAllWindows()
↧
↧
Using inpaint to restore old photo
I am trying to use OpenCV's built-in "inpaint" function to restore "damaged" areas of a photo (i.e: crease). However, after using the "inpaint" function, the resulting image contains a distortion in the mask area where inpaint was applied.
From my research, I believe inpainting is used to perform photo restoration. I am not sure if the distortion is occurring because I am not using the inpaint function correctly, or if there other functions/techniques that I must utilize in addition to inpaint?
Below is a code snippet that I am using to perform the inpaint: (OpenCV for iOS)
cv::Mat result;
// Convert UIImage to MAT
cv::Mat originalImage = [source CVMat3];
cv::Mat maskImage = [mask CVGrayscaleMat];
// Grayscale the mask and threshold it
cv::Mat maskMThresh;
cv::threshold(maskImage, maskMThresh, 100, 255, cv::THRESH_BINARY);
// Dilate the mask since thresholding has narrowed it slightly
cv::Mat dilatedMask;
cv::Mat dKernel(7, 7, CV_8U);
cv::dilate(maskMThresh, dilatedMask, dKernel);
// Apply inpaint effect
cv::inpaint(originalImage, dilatedMask, result, 3.0, cv::INPAINT_TELEA);
Below is a photo of the image that I am trying to restore. The mask region is colored red:

↧
Jupyter kernel crashes after running "train" for decision tree classifier
I tried to perform training on my data and on toy example too. Command prompt doesnt show anything but the message about restarting.
segm_features = np.array([[1,0], [1,1], [0,1]])
labels = np.array([1,0,0])
cv_model = cv.ml.DTrees_create()
dtype = np.int32
train_data = cv.ml.TrainData_create(segm_features.astype(np.float32), cv.ml.ROW_SAMPLE, labels.astype(dtype))
cv_model.train(train_data)
↧
Opencv 4.1.1 and Android Studio
Hello, i tried since three days to create a new project including opencv4.1.1 on Android Studio 3.4.2
I follow a lot of article but nothing append : when my app is starting, the opencv library won't initialize it ...
For example, i used this article (see the respone of Plo_Koon for opencv 4.1) : https://stackoverflow.com/questions/27406303/opencv-in-android-studio
Have you an idea for resolve my problem ???
Thanks
Thomas
↧