1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-31 00:03:03 +04:00

Merge branch 4.x

This commit is contained in:
Alexander Smorkalov
2025-02-05 09:28:27 +03:00
180 changed files with 11419 additions and 1819 deletions
+1 -1
View File
@@ -99,7 +99,7 @@ gradle.afterProject { project ->
// Android Gradle Plugin (AGP) 3.5+ is required
// https://github.com/android/ndk-samples/wiki/Configure-NDK-Path
def isNdkVersionSupported = project.android.metaClass.getProperties().find { it.name == 'ndkVersion' } != null
if ((false || opencv_strict_build_configuration) && isNdkVersionSupported) {
if (opencv_strict_build_configuration && isNdkVersionSupported) {
gradle.println("Override ndkVersion for the project ${project.name}")
project.android {
ndkVersion '@ANDROID_NDK_REVISION@'
@@ -14,10 +14,11 @@ android {
cmake {
if (gradle.opencv_source == "sdk_path") {
arguments "-DOpenCV_DIR=" + project(':opencv').projectDir + "/@ANDROID_PROJECT_JNI_PATH@",
"-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON",
"-DOPENCV_FROM_SDK=TRUE"@OPENCV_ANDROID_CMAKE_EXTRA_ARGS@
} else {
arguments "-DOPENCV_VERSION_MAJOR=@OPENCV_VERSION_MAJOR@",
"-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON",
"-DOPENCV_FROM_SDK=FALSE"@OPENCV_ANDROID_CMAKE_EXTRA_ARGS@
}
targets "mixed_sample"
@@ -14,6 +14,14 @@ endif()
message(STATUS "ANDROID_ABI=${ANDROID_ABI}")
find_package(OpenCV REQUIRED COMPONENTS ${ANDROID_OPENCV_COMPONENTS})
# For 16k pages support with NDK prior 27
# Details: https://developer.android.com/guide/practices/page-sizes?hl=en
if(ANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES)
if(ANDROID_ABI STREQUAL arm64-v8a OR ANDROID_ABI STREQUAL x86_64)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,max-page-size=16384")
endif()
endif()
file(GLOB srcs *.cpp *.c)
file(GLOB hdrs *.hpp *.h)
@@ -15,11 +15,13 @@ android {
if (gradle.opencv_source == "sdk_path") {
arguments "-DOpenCV_DIR=" + project(':opencv').projectDir + "/@ANDROID_PROJECT_JNI_PATH@",
"-DOPENCV_FROM_SDK=TRUE",
"-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON",
"-DANDROID_OPENCL_SDK=@ANDROID_OPENCL_SDK@" @OPENCV_ANDROID_CMAKE_EXTRA_ARGS@
} else {
arguments "-DOPENCV_VERSION_MAJOR=@OPENCV_VERSION_MAJOR@",
"-DOPENCV_FROM_SDK=FALSE",
"-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON",
"-DANDROID_OPENCL_SDK=@ANDROID_OPENCL_SDK@" @OPENCV_ANDROID_CMAKE_EXTRA_ARGS@
}
targets "JNIpart"
@@ -18,6 +18,14 @@ find_package(OpenCL QUIET)
file(GLOB srcs *.cpp *.c)
file(GLOB hdrs *.hpp *.h)
# For 16k pages support with NDK prior 27
# Details: https://developer.android.com/guide/practices/page-sizes?hl=en
if(ANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES)
if(ANDROID_ABI STREQUAL arm64-v8a OR ANDROID_ABI STREQUAL x86_64)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,max-page-size=16384")
endif()
endif()
include_directories("${CMAKE_CURRENT_LIST_DIR}")
add_library(${target} SHARED ${srcs} ${hdrs})
@@ -57,7 +57,6 @@ public class RecorderActivity extends CameraActivity implements CvCameraViewList
private VideoWriter mVideoWriter = null;
private VideoCapture mVideoCapture = null;
private Mat mVideoFrame;
private Mat mRenderFrame;
public RecorderActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
@@ -122,7 +121,6 @@ public class RecorderActivity extends CameraActivity implements CvCameraViewList
mTriggerButton.setText("Start Camera");
mVideoFrame.release();
mRenderFrame.release();
}
@Override
@@ -132,7 +130,6 @@ public class RecorderActivity extends CameraActivity implements CvCameraViewList
super.onResume();
mVideoFrame = new Mat();
mRenderFrame = new Mat();
changeStatus();
}
@@ -167,16 +164,15 @@ public class RecorderActivity extends CameraActivity implements CvCameraViewList
{
Log.d(TAG, "Camera frame arrived");
Mat rgbMat = inputFrame.rgba();
mVideoFrame = inputFrame.rgba();
Log.d(TAG, "Size: " + rgbMat.width() + "x" + rgbMat.height());
Log.d(TAG, "Size: " + mVideoFrame.width() + "x" + mVideoFrame.height());
if (mVideoWriter != null && mVideoWriter.isOpened()) {
Imgproc.cvtColor(rgbMat, mVideoFrame, Imgproc.COLOR_RGBA2BGR);
mVideoWriter.write(mVideoFrame);
}
return rgbMat;
return mVideoFrame;
}
@Override
@@ -294,12 +290,16 @@ public class RecorderActivity extends CameraActivity implements CvCameraViewList
mVideoCapture = new VideoCapture(mVideoFilename, Videoio.CAP_OPENCV_MJPEG);
}
if (!mVideoCapture.isOpened()) {
if (mVideoCapture == null || !mVideoCapture.isOpened()) {
Log.e(TAG, "Can't open video");
Toast.makeText(this, "Can't open file " + mVideoFilename, Toast.LENGTH_SHORT).show();
return false;
}
if (!mUseBuiltInMJPG){
mVideoCapture.set(Videoio.CAP_PROP_FOURCC, VideoWriter.fourcc('R','G','B','4'));
}
Toast.makeText(this, "Starting playback from file " + mVideoFilename, Toast.LENGTH_SHORT).show();
mPlayerThread = new Runnable() {
@@ -315,11 +315,14 @@ public class RecorderActivity extends CameraActivity implements CvCameraViewList
}
return;
}
// VideoCapture with CAP_ANDROID generates RGB frames instead of BGR
// https://github.com/opencv/opencv/issues/24687
Imgproc.cvtColor(mVideoFrame, mRenderFrame, mUseBuiltInMJPG ? Imgproc.COLOR_BGR2RGBA: Imgproc.COLOR_RGB2RGBA);
Bitmap bmp = Bitmap.createBitmap(mRenderFrame.cols(), mRenderFrame.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mRenderFrame, bmp);
// MJPEG codec will output BGR only. So we need to convert to RGBA.
if (mUseBuiltInMJPG) {
Imgproc.cvtColor(mVideoFrame, mVideoFrame, Imgproc.COLOR_BGR2RGBA);
}
Bitmap bmp = Bitmap.createBitmap(mVideoFrame.cols(), mVideoFrame.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mVideoFrame, bmp);
mImageView.setImageBitmap(bmp);
Handler h = new Handler();
h.postDelayed(this, 33);
@@ -27,12 +27,12 @@ Mat dst;
* @function on_trackbar
* @brief Callback for trackbar
*/
static void on_trackbar( int, void* )
{
alpha = (double) alpha_slider/alpha_slider_max ;
beta = ( 1.0 - alpha );
addWeighted( src1, alpha, src2, beta, 0.0, dst);
imshow( "Linear Blend", dst );
static void on_trackbar(int pos, void* userdata) {
(void) userdata;
alpha = (double)pos / alpha_slider_max;
beta = (1.0 - alpha);
addWeighted(src1, alpha, src2, beta, 0.0, dst);
imshow("Linear Blend", dst);
}
//![on_trackbar]
@@ -40,34 +40,35 @@ static void on_trackbar( int, void* )
* @function main
* @brief Main function
*/
int main( void )
int main(void)
{
//![load]
/// Read images ( both have to be of the same size and type )
src1 = imread( samples::findFile("LinuxLogo.jpg") );
src2 = imread( samples::findFile("WindowsLogo.jpg") );
//![load]
//![load]
/// Read images (both must be of the same size and type)
src1 = imread(samples::findFile("LinuxLogo.jpg"));
src2 = imread(samples::findFile("WindowsLogo.jpg"));
//![load]
if( src1.empty() ) { cout << "Error loading src1 \n"; return -1; }
if( src2.empty() ) { cout << "Error loading src2 \n"; return -1; }
if (src1.empty()) { cout << "Error loading src1 \n"; return -1; }
if (src2.empty()) { cout << "Error loading src2 \n"; return -1; }
/// Initialize values
alpha_slider = 0;
// Initialize trackbar value
alpha_slider = 0;
//![window]
namedWindow("Linear Blend", WINDOW_AUTOSIZE); // Create Window
//![window]
//![window]
namedWindow("Linear Blend", WINDOW_AUTOSIZE); //Create Window
//![window]
//![create_trackbar]
char TrackbarName[50];
snprintf( TrackbarName, sizeof(TrackbarName), "Alpha x %d", alpha_slider_max );
createTrackbar( TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar );
//![create_trackbar]
//![create_trackbar]
char TrackbarName[50];
snprintf(TrackbarName, sizeof(TrackbarName), "Alpha x %d", alpha_slider_max);
// Example userdata: Pass a pointer to an integer as userdata
createTrackbar(TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar);
//![create_trackbar]
/// Show some stuff
on_trackbar( alpha_slider, 0 );
/// Show initial result
on_trackbar(alpha_slider, nullptr);
/// Wait until user press some key
waitKey(0);
return 0;
/// Wait for user input
waitKey(0);
return 0;
}
@@ -15,22 +15,27 @@ using namespace std;
/// Global variables
/** General variables */
Mat src, edges;
Mat src, canny_edge, sobel_edge;
Mat src_gray;
Mat standard_hough, probabilistic_hough;
Mat standard_hough, probabilistic_hough, weighted_hough;
int min_threshold = 50;
int max_trackbar = 150;
int weightedhough_max_trackbar = 100000;
const char* standard_name = "Standard Hough Lines Demo";
const char* probabilistic_name = "Probabilistic Hough Lines Demo";
const char* weighted_name = "Weighted Hough Lines Demo";
int s_trackbar = max_trackbar;
int p_trackbar = max_trackbar;
int e_trackbar = 60;
int w_trackbar = 60000;
/// Function Headers
void help();
void Standard_Hough( int, void* );
void Probabilistic_Hough( int, void* );
void Weighted_Hough( int, void* );
/**
* @function main
@@ -53,22 +58,29 @@ int main( int argc, char** argv )
/// Pass the image to gray
cvtColor( src, src_gray, COLOR_RGB2GRAY );
/// Apply Canny edge detector
Canny( src_gray, edges, 50, 200, 3 );
/// Apply Canny/Sobel edge detector
Canny( src_gray, canny_edge, 50, 200, 3 );
Sobel( src_gray, sobel_edge, CV_16S, 1, 0 ); // dx(order of the derivative x)=1,dy=0
/// Create Trackbars for Thresholds
char thresh_label[50];
snprintf( thresh_label, sizeof(thresh_label), "Thres: %d + input", min_threshold );
namedWindow( standard_name, WINDOW_AUTOSIZE );
createTrackbar( thresh_label, standard_name, &s_trackbar, max_trackbar, Standard_Hough);
createTrackbar( thresh_label, standard_name, &s_trackbar, max_trackbar, Standard_Hough );
namedWindow( probabilistic_name, WINDOW_AUTOSIZE );
createTrackbar( thresh_label, probabilistic_name, &p_trackbar, max_trackbar, Probabilistic_Hough);
createTrackbar( thresh_label, probabilistic_name, &p_trackbar, max_trackbar, Probabilistic_Hough );
char edge_thresh_label[50];
sprintf( edge_thresh_label, "Edge Thres: input" );
namedWindow( weighted_name, WINDOW_AUTOSIZE);
createTrackbar( edge_thresh_label, weighted_name, &e_trackbar, max_trackbar, Weighted_Hough);
createTrackbar( thresh_label, weighted_name, &w_trackbar, weightedhough_max_trackbar, Weighted_Hough);
/// Initialize
Standard_Hough(0, 0);
Probabilistic_Hough(0, 0);
Weighted_Hough(0, 0);
waitKey(0);
return 0;
}
@@ -90,10 +102,10 @@ void help()
void Standard_Hough( int, void* )
{
vector<Vec2f> s_lines;
cvtColor( edges, standard_hough, COLOR_GRAY2BGR );
cvtColor( canny_edge, standard_hough, COLOR_GRAY2BGR );
/// 1. Use Standard Hough Transform
HoughLines( edges, s_lines, 1, CV_PI/180, min_threshold + s_trackbar, 0, 0 );
HoughLines( canny_edge, s_lines, 1, CV_PI/180, min_threshold + s_trackbar, 0, 0 );
/// Show the result
for( size_t i = 0; i < s_lines.size(); i++ )
@@ -117,10 +129,10 @@ void Standard_Hough( int, void* )
void Probabilistic_Hough( int, void* )
{
vector<Vec4i> p_lines;
cvtColor( edges, probabilistic_hough, COLOR_GRAY2BGR );
cvtColor( canny_edge, probabilistic_hough, COLOR_GRAY2BGR );
/// 2. Use Probabilistic Hough Transform
HoughLinesP( edges, p_lines, 1, CV_PI/180, min_threshold + p_trackbar, 30, 10 );
HoughLinesP( canny_edge, p_lines, 1, CV_PI/180, min_threshold + p_trackbar, 30, 10 );
/// Show the result
for( size_t i = 0; i < p_lines.size(); i++ )
@@ -131,3 +143,38 @@ void Probabilistic_Hough( int, void* )
imshow( probabilistic_name, probabilistic_hough );
}
/**
* @function Weighted_Hough
* This can detect lines based on the edge intensities.
*/
void Weighted_Hough( int, void* )
{
vector<Vec2f> s_lines;
/// prepare
Mat edge_img;
convertScaleAbs(sobel_edge, edge_img );
// use same threshold for edge with Hough.
threshold( edge_img, edge_img, e_trackbar, 255, cv::THRESH_TOZERO);
cvtColor( edge_img, weighted_hough, COLOR_GRAY2BGR );
/// 3. Use Weighted Hough Transform
const bool use_edgeval{true};
HoughLines( edge_img, s_lines, 1, CV_PI/180, min_threshold + w_trackbar, 0, 0, 0, CV_PI, use_edgeval);
/// Show the result
for( size_t i = 0; i < s_lines.size(); i++ )
{
float r = s_lines[i][0], t = s_lines[i][1];
double cos_t = cos(t), sin_t = sin(t);
double x0 = r*cos_t, y0 = r*sin_t;
double alpha = 1000;
Point pt1( cvRound(x0 + alpha*(-sin_t)), cvRound(y0 + alpha*cos_t) );
Point pt2( cvRound(x0 - alpha*(-sin_t)), cvRound(y0 - alpha*cos_t) );
line( weighted_hough, pt1, pt2, Scalar(255,0,0), 3, LINE_AA );
}
imshow( weighted_name, weighted_hough );
}
@@ -0,0 +1,51 @@
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
using namespace cv;
int main( int argc, const char** argv )
{
std::string filename = argc > 1 ? argv[1] : "animated_image.webp";
//! [write_animation]
if (argc == 1)
{
Animation animation_to_save;
Mat image(128, 256, CV_8UC4, Scalar(150, 150, 150, 255));
int duration = 200;
for (int i = 0; i < 10; ++i) {
animation_to_save.frames.push_back(image.clone());
putText(animation_to_save.frames[i], format("Frame %d", i), Point(30, 80), FONT_HERSHEY_SIMPLEX, 1.5, Scalar(255, 100, 0, 255), 2);
animation_to_save.durations.push_back(duration);
}
imwriteanimation("animated_image.webp", animation_to_save, { IMWRITE_WEBP_QUALITY, 100 });
}
//! [write_animation]
//! [init_animation]
Animation animation;
//! [init_animation]
//! [read_animation]
bool success = imreadanimation(filename, animation);
if (!success) {
std::cerr << "Failed to load animation frames\n";
return -1;
}
//! [read_animation]
//! [show_animation]
while (true)
for (size_t i = 0; i < animation.frames.size(); ++i) {
imshow("Animation", animation.frames[i]);
int key_code = waitKey(animation.durations[i]); // Delay between frames
if (key_code == 27)
exit(0);
}
//! [show_animation]
return 0;
}
@@ -0,0 +1,52 @@
import cv2 as cv
import numpy as np
def main(filename):
## [write_animation]
if filename == "animated_image.webp":
# Create an Animation instance to save
animation_to_save = cv.Animation()
# Generate a base image with a specific color
image = np.full((128, 256, 4), (150, 150, 150, 255), dtype=np.uint8)
duration = 200
frames = []
durations = []
# Populate frames and durations in the Animation object
for i in range(10):
frame = image.copy()
cv.putText(frame, f"Frame {i}", (30, 80), cv.FONT_HERSHEY_SIMPLEX, 1.5, (255, 100, 0, 255), 2)
frames.append(frame)
durations.append(duration)
animation_to_save.frames = frames
animation_to_save.durations = durations
# Write the animation to file
cv.imwriteanimation(filename, animation_to_save, [cv.IMWRITE_WEBP_QUALITY, 100])
## [write_animation]
## [init_animation]
animation = cv.Animation()
## [init_animation]
## [read_animation]
success, animation = cv.imreadanimation(filename)
if not success:
print("Failed to load animation frames")
return
## [read_animation]
## [show_animation]
while True:
for i, frame in enumerate(animation.frames):
cv.imshow("Animation", frame)
key_code = cv.waitKey(animation.durations[i])
if key_code == 27: # Exit if 'Esc' key is pressed
return
## [show_animation]
if __name__ == "__main__":
import sys
main(sys.argv[1] if len(sys.argv) > 1 else "animated_image.webp")