├── .gitignore ├── ITEM 1-9 ├── ITEM1 age_gender │ ├── age_gender.cpp │ ├── age_gender.py │ └── images │ │ ├── couple.jpg │ │ └── sample.jpg ├── ITEM2 Opencv_dlib_face_detection │ ├── dnn_opencv.cpp │ ├── face_detection.cpp │ ├── face_detection.h │ ├── face_detection_opencv_dnn.py │ ├── face_detection_opencv_haar.py │ └── haar_opencv.cpp ├── ITEM3 invisibility_cloak │ ├── Invisibility_cloak.py │ ├── invisibility_cloak.cpp │ └── video │ │ └── download.txt ├── ITEM5 text_detection │ ├── image │ │ ├── slippery.jpg │ │ ├── stop1.jpg │ │ └── stop2.jpg │ ├── text_detection.cpp │ └── text_detection.py ├── ITEM6 video_stabilization │ ├── video │ │ └── download.txt │ ├── video_stabilization.cpp │ └── video_stabilization.py ├── ITEM7 yolov3_detect │ ├── image │ │ ├── test1.jpg │ │ └── test2.jpg │ ├── model │ │ ├── coco.names │ │ └── yolov3.cfg │ ├── yolov3_detect.cpp │ └── yolov3_detect.py ├── ITEM8 training_YOLOv3 │ ├── OpenImageV4 │ │ ├── OpenImages_linux.py │ │ ├── OpenImages_windows.py │ │ ├── README.md │ │ └── splitTrainAndTest.py │ ├── README.md │ └── snowman │ │ ├── classes.names │ │ ├── darknet-yolov3.cfg │ │ ├── darknet.data │ │ └── plotTrainLoss.py └── ITEM9 centroid_blob │ ├── image │ ├── circle.png │ └── multiple.png │ ├── multiple_blob.cpp │ ├── multiple_blob.py │ ├── single_blob.cpp │ └── single_blob.py ├── ITEM 10-19 ├── ITEM10 HuMoments │ ├── HuMoments.cpp │ ├── HuMoments.py │ ├── image │ │ ├── K0.png │ │ ├── S0.png │ │ ├── S1.png │ │ ├── S2.png │ │ ├── S3.png │ │ ├── S4.png │ │ └── S5.png │ ├── shapeMatcher.cpp │ └── shapeMatcher.py ├── ITEM11 QRCode_scanner │ ├── Image │ │ └── demo.jpg │ ├── QRCode_scanner.cpp │ └── QRCode_scanner.py ├── ITEM12 HandPoints_detection │ ├── HandPoints_detection.cpp │ ├── handPoseImage.py │ ├── image │ │ ├── hand.jpg │ │ └── hand_other.jpg │ └── model │ │ ├── getModels.sh │ │ └── pose_deploy.prototxt ├── ITEM13 Mask R-CNN in OpenCV │ ├── Mask R-CNN in OpenCV.cpp │ ├── Mask R-CNN in OpenCV.py │ ├── image │ │ └── cars.jpg │ └── model │ │ ├── colors.txt │ │ ├── mask_rcnn_inception_v2_coco.pbtxt │ │ └── mscoco_labels.names ├── ITEM14 Opencv_SingleTracker │ ├── Opencv_SingleTracker.cpp │ ├── Opencv_SingleTracker.py │ └── video │ │ └── download.txt ├── ITEM15 GOTURN_SingleTracker │ ├── GOTURN_SingleTracker.cpp │ ├── GOTURN_SingleTracker.py │ ├── goturn.prototxt │ └── video │ │ └── download.txt ├── ITEM16 OpenCV_MultiTracker │ ├── Opencv_MultiTracker.cpp │ ├── Opencv_MultiTracker.py │ └── video │ │ └── download.txt ├── ITEM17 OpenCV_Colorization │ ├── OpenCV_ImageColorization.cpp │ ├── OpenCV_ImageColorization.py │ ├── OpenCV_VideoColorization.cpp │ ├── OpenCV_VideoColorization.py │ ├── image │ │ └── greyscaleImage.png │ ├── model │ │ ├── colorization_deploy_v2.prototxt │ │ └── pts_in_hull.npy │ └── video │ │ └── greyscaleVideo.mp4 ├── ITEM18 OpenCV_Homography │ ├── OpenCV_Homography.cpp │ ├── OpenCV_Homography.py │ ├── image │ │ ├── book1.jpg │ │ └── book2.jpg │ └── virtual-billboard │ │ ├── first-image.jpg │ │ ├── times-square.jpg │ │ ├── utils.py │ │ ├── virtual-billboard.cpp │ │ └── virtual-billboard.py └── ITEM19 OpenCV_Align │ ├── OpenCV_Align.cpp │ ├── OpenCV_Align.py │ └── image │ ├── form.jpg │ └── scanned-form.jpg ├── ITEM 20-29 ├── ITEM20 OpenCV_ECCAlignment │ ├── OpenCV_ECCAlignment.cpp │ ├── OpenCV_ECCAlignment.py │ ├── OpenCV_ECCAlignment_example.cpp │ ├── OpenCV_ECCAlignment_example.py │ └── image │ │ ├── bridge.jpg │ │ ├── emir.jpg │ │ ├── girls.jpg │ │ ├── image1.jpg │ │ └── image2.jpg ├── ITEM21 OpenCV_EigenFace │ ├── OpenCV_EigenFace.cpp │ ├── OpenCV_EigenFace.py │ ├── dirent.h │ ├── image │ │ └── download.txt │ └── pch.cpp ├── ITEM22 reconstructFace │ ├── createPCAModel.cpp │ ├── createPCAModel.py │ ├── dirent.h │ ├── image │ │ └── download.txt │ ├── reconstructFace.cpp │ ├── reconstructFace.py │ └── test │ │ ├── satya1.jpg │ │ └── satya2.jpg ├── ITEM23 OpenCV_HDR │ ├── OpenCV_HDR.cpp │ ├── OpenCV_HDR.py │ └── image │ │ └── download.txt ├── ITEM24 OpenCV_ExposureFusion │ ├── OpenCV_ExposureFusion.cpp │ ├── OpenCV_ExposureFusion.py │ └── image │ │ └── download.txt ├── ITEM25 OpenCV_SeamlessCloning │ ├── OpenCV_SeamlessCloning.cpp │ ├── OpenCV_SeamlessCloning.py │ ├── image │ │ ├── airplane.jpg │ │ ├── iloveyouticket.jpg │ │ ├── sky.jpg │ │ └── wood-texture.jpg │ ├── normal_versus_mixed_clone.cpp │ └── normal_versus_mixed_clone.py ├── ITEM26 OpenCV_SelectiveSearch │ ├── OpenCV_SelectiveSearch.cpp │ ├── OpenCV_SelectiveSearch.py │ └── image │ │ ├── breakfast.jpg │ │ └── dogs.jpg ├── ITEM27 OpenCV_forEach │ ├── OpenCV_forEach.cpp │ └── image │ │ └── butterfly.jpg ├── ITEM28 OpenCV_cvui │ ├── canny.cpp │ ├── cvui.h │ ├── hello-world.cpp │ └── image │ │ └── lena.jpg └── ITEM29 OpenCV_RedEyeRemover │ ├── OpenCV_RedEyeRemover.cpp │ ├── OpenCV_RedEyeRemover.py │ ├── image │ ├── red_eyes.jpg │ └── red_eyes2.jpg │ └── model │ └── haarcascade_eye.xml ├── ITEM 30-39 ├── ITEM30 OpenCV_FillHoles │ ├── OpenCV_FillHoles.cpp │ ├── OpenCV_FillHoles.py │ └── image │ │ └── nickel.jpg ├── ITEM31 OpenCV_WarpTriangle │ ├── OpenCV_WarpTriangle.cpp │ ├── OpenCV_WarpTriangle.py │ └── image │ │ └── robot.jpg ├── ITEM32 OpenCV_NonPhotorealisticRendering │ ├── OpenCV_NonPhotorealisticRendering.cpp │ ├── OpenCV_NonPhotorealisticRendering.py │ └── image │ │ └── cow.jpg ├── ITEM33 OpenCV_HoughTransform │ ├── hough_circles.cpp │ ├── hough_circles.py │ ├── hough_lines.cpp │ ├── hough_lines.py │ └── image │ │ ├── brown-eyes.jpg │ │ └── lanes.jpg ├── ITEM34 OpenCV_Inpainting │ ├── OpenCV_Inpainting.cpp │ ├── OpenCV_Inpainting.py │ └── image │ │ ├── Lincoln.jpg │ │ ├── flower-garden.jpg │ │ └── sample.jpeg ├── ITEM35 OpenCV_Tesseract │ ├── OpenCV_Tesseract.cpp │ ├── OpenCV_Tesseract.py │ └── image │ │ ├── computer-vision.jpg │ │ ├── receipt.png │ │ ├── road-sign-1.jpg │ │ ├── road-sign-2.jpg │ │ └── road-sign-3.jpg ├── ITEM36 OpenCV_BackgroundEstimation │ ├── OpenCV_BackgroundEstimation.cpp │ ├── OpenCV_BackgroundEstimation.py │ └── video │ │ └── download.txt ├── ITEM37 OpenCV_BRISQUE │ ├── allmodel │ ├── allrange │ ├── brisque.cpp │ ├── brisque.h │ ├── brisquequality.py │ ├── computescore.cpp │ ├── images │ │ ├── JPEG2k-compressed.jpg │ │ ├── blur-vision.jpg │ │ ├── compressed-heavy.jpg │ │ ├── noise-version.jpg │ │ ├── original-rotated-image.jpg │ │ └── original-scaled-image.jpg │ ├── libsvm │ │ ├── COPYRIGHT │ │ ├── FAQ.html │ │ ├── Makefile │ │ ├── Makefile.win │ │ ├── README │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ └── __init__.cpython-36.pyc │ │ ├── heart_scale │ │ ├── java │ │ │ ├── Makefile │ │ │ ├── libsvm.jar │ │ │ ├── libsvm │ │ │ │ ├── svm.java │ │ │ │ ├── svm.m4 │ │ │ │ ├── svm_model.java │ │ │ │ ├── svm_node.java │ │ │ │ ├── svm_parameter.java │ │ │ │ ├── svm_print_interface.java │ │ │ │ └── svm_problem.java │ │ │ ├── svm_predict.java │ │ │ ├── svm_scale.java │ │ │ ├── svm_toy.java │ │ │ ├── svm_train.java │ │ │ └── test_applet.html │ │ ├── libsvm.so.2 │ │ ├── matlab │ │ │ ├── Makefile │ │ │ ├── README │ │ │ ├── libsvmread.c │ │ │ ├── libsvmwrite.c │ │ │ ├── make.m │ │ │ ├── svm_model_matlab.c │ │ │ ├── svm_model_matlab.h │ │ │ ├── svmpredict.c │ │ │ └── svmtrain.c │ │ ├── python │ │ │ ├── Makefile │ │ │ ├── README │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── __init__.cpython-36.pyc │ │ │ │ ├── svm.cpython-35.pyc │ │ │ │ ├── svm.cpython-36.pyc │ │ │ │ ├── svmutil.cpython-35.pyc │ │ │ │ └── svmutil.cpython-36.pyc │ │ │ ├── allmodel │ │ │ ├── brisquequality.py │ │ │ ├── svm.py │ │ │ └── svmutil.py │ │ ├── svm-predict │ │ ├── svm-predict.c │ │ ├── svm-scale │ │ ├── svm-scale.c │ │ ├── svm-toy │ │ │ ├── gtk │ │ │ │ ├── Makefile │ │ │ │ ├── callbacks.cpp │ │ │ │ ├── callbacks.h │ │ │ │ ├── interface.c │ │ │ │ ├── interface.h │ │ │ │ ├── main.c │ │ │ │ └── svm-toy.glade │ │ │ ├── qt │ │ │ │ ├── Makefile │ │ │ │ └── svm-toy.cpp │ │ │ └── windows │ │ │ │ └── svm-toy.cpp │ │ ├── svm-train │ │ ├── svm-train.c │ │ ├── svm.cpp │ │ ├── svm.def │ │ ├── svm.h │ │ ├── tools │ │ │ ├── README │ │ │ ├── checkdata.py │ │ │ ├── easy.py │ │ │ ├── grid.py │ │ │ └── subset.py │ │ └── windows │ │ │ ├── libsvmread.mexw64 │ │ │ ├── libsvmwrite.mexw64 │ │ │ ├── svmpredict.mexw64 │ │ │ └── svmtrain.mexw64 │ └── main.cpp ├── ITEM38 OpenCV_CameraCalibration │ ├── OpenCV_CameraCalibration.cpp │ ├── OpenCV_CameraCalibration.py │ └── images │ │ ├── image_10.jpg │ │ ├── image_11.jpg │ │ ├── image_12.jpg │ │ ├── image_14.jpg │ │ ├── image_15.jpg │ │ ├── image_18.jpg │ │ ├── image_19.jpg │ │ ├── image_2.jpg │ │ ├── image_20.jpg │ │ ├── image_21.jpg │ │ ├── image_22.jpg │ │ ├── image_23.jpg │ │ ├── image_24.jpg │ │ ├── image_25.jpg │ │ ├── image_26.jpg │ │ ├── image_27.jpg │ │ ├── image_29.jpg │ │ ├── image_30.jpg │ │ ├── image_40.jpg │ │ ├── image_41.jpg │ │ ├── image_42.jpg │ │ ├── image_43.jpg │ │ ├── image_44.jpg │ │ ├── image_46.jpg │ │ ├── image_47.jpg │ │ ├── image_48.jpg │ │ ├── image_49.jpg │ │ ├── image_5.jpg │ │ ├── image_50.jpg │ │ ├── image_57.jpg │ │ ├── image_6.jpg │ │ ├── image_62.jpg │ │ ├── image_64.jpg │ │ ├── image_65.jpg │ │ ├── image_70.jpg │ │ ├── image_71.jpg │ │ ├── image_72.jpg │ │ ├── image_73.jpg │ │ ├── image_75.jpg │ │ ├── image_8.jpg │ │ └── image_9.jpg └── ITEM39 OpenCV_ArUco │ ├── augmented_reality_with_aruco.cpp │ ├── augmented_reality_with_aruco.py │ ├── generate_aruco_markers.cpp │ ├── generate_aruco_markers.py │ ├── image │ ├── new_scenery.jpg │ └── test.jpg │ └── video │ └── test.mp4 ├── ITEM 40-49 ├── ITEM43 OpenCV_Bgsegm │ ├── OpenCV_Bgsegm.cpp │ ├── OpenCV_Bgsegm.py │ └── video │ │ └── download.txt ├── ITEM44 OpenCV_ImageSuperres │ ├── dnn_superres.cpp │ ├── dnn_superres.py │ ├── dnn_superres_benchmark_quality.cpp │ ├── dnn_superres_benchmark_quality.py │ ├── dnn_superres_benchmark_time.cpp │ ├── dnn_superres_benchmark_time.py │ ├── dnn_superres_multioutput.cpp │ ├── dnn_superres_video.cpp │ ├── dnn_superres_video.py │ └── image │ │ ├── butterfly.png │ │ └── image.png ├── ITEM45 OpenCV_ImgHash │ ├── OpenCV_ImgHash.cpp │ ├── OpenCV_ImgHash.py │ └── image │ │ ├── img1.jpg │ │ ├── img2.jpg │ │ ├── img3.jpg │ │ └── img4.jpg ├── ITEM46 OpenCV_IntensityTransform │ ├── OpenCV_IntensityTransform.cpp │ ├── OpenCV_IntensityTransform.py │ └── image │ │ ├── car.png │ │ ├── indicator.jpg │ │ ├── tree.jpg │ │ └── xray.jpg ├── ITEM47 OpenCV_SaliencyObject │ ├── ObjectnessTrainedModel │ │ ├── ObjNessB2W8HSV.idx.yml.gz │ │ ├── ObjNessB2W8HSV.wS1.yml.gz │ │ ├── ObjNessB2W8HSV.wS2.yml.gz │ │ ├── ObjNessB2W8I.idx.yml.gz │ │ ├── ObjNessB2W8I.wS1.yml.gz │ │ ├── ObjNessB2W8I.wS2.yml.gz │ │ ├── ObjNessB2W8MAXBGR.idx.yml.gz │ │ ├── ObjNessB2W8MAXBGR.wS1.yml.gz │ │ └── ObjNessB2W8MAXBGR.wS2.yml.gz │ ├── OpenCV_SaliencyObject.cpp │ ├── OpenCV_SaliencyObject.py │ └── video │ │ ├── dog.jpg │ │ └── download.txt ├── ITEM48 OpenCV_ImageQuality │ ├── OpenCV_ImageQuality.cpp │ ├── OpenCV_ImageQuality.py │ ├── image │ │ ├── blur-vision.jpg │ │ ├── cut-blur-vision.jpg │ │ ├── cut-noise-version.jpg │ │ ├── cut-original-rotated-image.jpg │ │ ├── noise-version.jpg │ │ └── original-rotated-image.jpg │ └── model │ │ ├── brisque_model_live.yml │ │ └── brisque_range_live.yml └── ITEM49 OpenCV_StereoDisparity │ ├── OpenCV_StereoDisparity.cpp │ ├── OpenCV_StereoDisparity.py │ └── images │ ├── im0.png │ └── im1.png ├── ITEM 50-59 ├── ITEM50 OpenCV_StereoCamera │ ├── calibrate.cpp │ ├── calibrate.py │ ├── data │ │ └── download.txt │ ├── movie3d.cpp │ └── movie3d.py ├── ITEM51 OpenCV_Polar │ ├── OpenCV_Polar.cpp │ ├── OpenCV_Polar.py │ ├── OpenCV_WarpPolar.cpp │ ├── OpenCV_WarpPolar.py │ └── image │ │ └── clock.jpg └── ITEM52 OpenCV_Histogram │ ├── 1calcHist_use.cpp │ ├── 1calcHist_use.py │ ├── 2equalizeHist_use.cpp │ ├── 2equalizeHist_use.py │ ├── 3createCLAHE_use.cpp │ ├── 3createCLAHE_use.py │ ├── 4equalizeHist_color.cpp │ ├── 4equalizeHist_color.py │ ├── 5compareHist_use.cpp │ ├── 5compareHist_use.py │ ├── 6calcBackProject_use.cpp │ ├── 6calcBackProject_use.py │ └── image │ ├── lena.jpg │ ├── lena_flip.jpg │ ├── lena_resize.jpg │ ├── test.jpg │ ├── test2.jpg │ └── test3.jpg ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | -------------------------------------------------------------------------------- /ITEM 1-9/ITEM1 age_gender/age_gender.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM1 age_gender/age_gender.cpp -------------------------------------------------------------------------------- /ITEM 1-9/ITEM1 age_gender/age_gender.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM1 age_gender/age_gender.py -------------------------------------------------------------------------------- /ITEM 1-9/ITEM1 age_gender/images/couple.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM1 age_gender/images/couple.jpg -------------------------------------------------------------------------------- /ITEM 1-9/ITEM1 age_gender/images/sample.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM1 age_gender/images/sample.jpg -------------------------------------------------------------------------------- /ITEM 1-9/ITEM2 Opencv_dlib_face_detection/dnn_opencv.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM2 Opencv_dlib_face_detection/dnn_opencv.cpp -------------------------------------------------------------------------------- /ITEM 1-9/ITEM2 Opencv_dlib_face_detection/face_detection.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM2 Opencv_dlib_face_detection/face_detection.cpp -------------------------------------------------------------------------------- /ITEM 1-9/ITEM2 Opencv_dlib_face_detection/face_detection.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM2 Opencv_dlib_face_detection/face_detection.h -------------------------------------------------------------------------------- /ITEM 1-9/ITEM2 Opencv_dlib_face_detection/face_detection_opencv_haar.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import cv2 3 | import time 4 | import sys 5 | 6 | def detectFaceOpenCVHaar(faceCascade, frame, inHeight=300, inWidth=0): 7 | frameOpenCVHaar = frame.copy() 8 | frameHeight = frameOpenCVHaar.shape[0] 9 | frameWidth = frameOpenCVHaar.shape[1] 10 | if not inWidth: 11 | inWidth = int((frameWidth / frameHeight) * inHeight) 12 | 13 | scaleHeight = frameHeight / inHeight 14 | scaleWidth = frameWidth / inWidth 15 | 16 | frameOpenCVHaarSmall = cv2.resize(frameOpenCVHaar, (inWidth, inHeight)) 17 | frameGray = cv2.cvtColor(frameOpenCVHaarSmall, cv2.COLOR_BGR2GRAY) 18 | 19 | faces = faceCascade.detectMultiScale(frameGray) 20 | bboxes = [] 21 | for (x, y, w, h) in faces: 22 | x1 = x 23 | y1 = y 24 | x2 = x + w 25 | y2 = y + h 26 | cvRect = [int(x1 * scaleWidth), int(y1 * scaleHeight), 27 | int(x2 * scaleWidth), int(y2 * scaleHeight)] 28 | bboxes.append(cvRect) 29 | cv2.rectangle(frameOpenCVHaar, (cvRect[0], cvRect[1]), (cvRect[2], cvRect[3]), (0, 255, 0), 30 | int(round(frameHeight / 150)), 4) 31 | return frameOpenCVHaar, bboxes 32 | 33 | if __name__ == "__main__" : 34 | source = 0 35 | if len(sys.argv) > 1: 36 | source = sys.argv[1] 37 | 38 | faceCascade = cv2.CascadeClassifier('./model/haarcascade_frontalface_default.xml') 39 | 40 | cap = cv2.VideoCapture(source) 41 | hasFrame, frame = cap.read() 42 | 43 | vid_writer = cv2.VideoWriter('output-haar-{}.avi'.format(str(source).split(".")[0]),cv2.VideoWriter_fourcc('M','J','P','G'), 15, (frame.shape[1],frame.shape[0])) 44 | 45 | frame_count = 0 46 | tt_opencvHaar = 0 47 | while(1): 48 | hasFrame, frame = cap.read() 49 | if not hasFrame: 50 | break 51 | frame_count += 1 52 | 53 | t = time.time() 54 | outOpencvHaar, bboxes = detectFaceOpenCVHaar(faceCascade, frame) 55 | tt_opencvHaar += time.time() - t 56 | fpsOpencvHaar = frame_count / tt_opencvHaar 57 | 58 | label = "OpenCV Haar ; FPS : {:.2f}".format(fpsOpencvHaar) 59 | cv2.putText(outOpencvHaar, label, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, cv2.LINE_AA) 60 | 61 | cv2.imshow("Face Detection Comparison", outOpencvHaar) 62 | 63 | vid_writer.write(outOpencvHaar) 64 | if frame_count == 1: 65 | tt_opencvHaar = 0 66 | 67 | k = cv2.waitKey(10) 68 | if k == 27: 69 | break 70 | cv2.destroyAllWindows() 71 | vid_writer.release() 72 | 73 | -------------------------------------------------------------------------------- /ITEM 1-9/ITEM2 Opencv_dlib_face_detection/haar_opencv.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM2 Opencv_dlib_face_detection/haar_opencv.cpp -------------------------------------------------------------------------------- /ITEM 1-9/ITEM3 invisibility_cloak/Invisibility_cloak.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import time 4 | 5 | 6 | # Creating an VideoCapture object 7 | # This will be used for image acquisition later in the code. 8 | cap = cv2.VideoCapture('video/detect.mp4') 9 | 10 | if cap.isOpened: 11 | print("your video is opened") 12 | # We give some time for the camera to setup 13 | time.sleep(3) 14 | count = 0 15 | background=0 16 | 17 | # Capturing and storing the static background frame 18 | for i in range(60): 19 | ret,background = cap.read() 20 | 21 | background = np.flip(background,axis=1) 22 | 23 | 24 | #跳帧 25 | for i in range(200): 26 | slip_frame = cap.read() 27 | while(cap.isOpened()): 28 | 29 | ret, img = cap.read() 30 | if not ret: 31 | break 32 | count+=1 33 | img = np.flip(img,axis=1) 34 | 35 | # Converting the color space from BGR to HSV 36 | hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) 37 | 38 | # Generating mask to detect red color 39 | lower_red = np.array([0,120,70]) 40 | upper_red = np.array([10,255,255]) 41 | mask1 = cv2.inRange(hsv,lower_red,upper_red) 42 | 43 | lower_red = np.array([170,120,70]) 44 | upper_red = np.array([180,255,255]) 45 | mask2 = cv2.inRange(hsv,lower_red,upper_red) 46 | 47 | mask1 = mask1+mask2 48 | 49 | # Refining the mask corresponding to the detected red color 50 | mask1 = cv2.morphologyEx(mask1, cv2.MORPH_OPEN, np.ones((3,3),np.uint8),iterations=2) 51 | mask1 = cv2.dilate(mask1,np.ones((3,3),np.uint8),iterations = 1) 52 | mask2 = cv2.bitwise_not(mask1) 53 | 54 | # Generating the final output 55 | res1 = cv2.bitwise_and(background,background,mask=mask1) 56 | res2 = cv2.bitwise_and(img,img,mask=mask2) 57 | final_output = cv2.addWeighted(res1,1,res2,1,0) 58 | 59 | cv2.imshow('Magic !!!',final_output) 60 | k = cv2.waitKey(10) 61 | if k == 27: 62 | break 63 | -------------------------------------------------------------------------------- /ITEM 1-9/ITEM3 invisibility_cloak/invisibility_cloak.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM3 invisibility_cloak/invisibility_cloak.cpp -------------------------------------------------------------------------------- /ITEM 1-9/ITEM3 invisibility_cloak/video/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/luohenyueji/OpenCV-Model-ZOO/tree/master/OpenCV-Practical-Exercise-Model/videos -------------------------------------------------------------------------------- /ITEM 1-9/ITEM5 text_detection/image/slippery.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM5 text_detection/image/slippery.jpg -------------------------------------------------------------------------------- /ITEM 1-9/ITEM5 text_detection/image/stop1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM5 text_detection/image/stop1.jpg -------------------------------------------------------------------------------- /ITEM 1-9/ITEM5 text_detection/image/stop2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM5 text_detection/image/stop2.jpg -------------------------------------------------------------------------------- /ITEM 1-9/ITEM5 text_detection/text_detection.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM5 text_detection/text_detection.cpp -------------------------------------------------------------------------------- /ITEM 1-9/ITEM5 text_detection/text_detection.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM5 text_detection/text_detection.py -------------------------------------------------------------------------------- /ITEM 1-9/ITEM6 video_stabilization/video/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/luohenyueji/OpenCV-Model-ZOO/tree/master/OpenCV-Practical-Exercise-Model/videos -------------------------------------------------------------------------------- /ITEM 1-9/ITEM6 video_stabilization/video_stabilization.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM6 video_stabilization/video_stabilization.cpp -------------------------------------------------------------------------------- /ITEM 1-9/ITEM7 yolov3_detect/image/test1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM7 yolov3_detect/image/test1.jpg -------------------------------------------------------------------------------- /ITEM 1-9/ITEM7 yolov3_detect/image/test2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM7 yolov3_detect/image/test2.jpg -------------------------------------------------------------------------------- /ITEM 1-9/ITEM7 yolov3_detect/model/coco.names: -------------------------------------------------------------------------------- 1 | person 2 | bicycle 3 | car 4 | motorbike 5 | aeroplane 6 | bus 7 | train 8 | truck 9 | boat 10 | traffic light 11 | fire hydrant 12 | stop sign 13 | parking meter 14 | bench 15 | bird 16 | cat 17 | dog 18 | horse 19 | sheep 20 | cow 21 | elephant 22 | bear 23 | zebra 24 | giraffe 25 | backpack 26 | umbrella 27 | handbag 28 | tie 29 | suitcase 30 | frisbee 31 | skis 32 | snowboard 33 | sports ball 34 | kite 35 | baseball bat 36 | baseball glove 37 | skateboard 38 | surfboard 39 | tennis racket 40 | bottle 41 | wine glass 42 | cup 43 | fork 44 | knife 45 | spoon 46 | bowl 47 | banana 48 | apple 49 | sandwich 50 | orange 51 | broccoli 52 | carrot 53 | hot dog 54 | pizza 55 | donut 56 | cake 57 | chair 58 | sofa 59 | pottedplant 60 | bed 61 | diningtable 62 | toilet 63 | tvmonitor 64 | laptop 65 | mouse 66 | remote 67 | keyboard 68 | cell phone 69 | microwave 70 | oven 71 | toaster 72 | sink 73 | refrigerator 74 | book 75 | clock 76 | vase 77 | scissors 78 | teddy bear 79 | hair drier 80 | toothbrush 81 | -------------------------------------------------------------------------------- /ITEM 1-9/ITEM7 yolov3_detect/yolov3_detect.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM7 yolov3_detect/yolov3_detect.cpp -------------------------------------------------------------------------------- /ITEM 1-9/ITEM7 yolov3_detect/yolov3_detect.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM7 yolov3_detect/yolov3_detect.py -------------------------------------------------------------------------------- /ITEM 1-9/ITEM8 training_YOLOv3/OpenImageV4/OpenImages_linux.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM8 training_YOLOv3/OpenImageV4/OpenImages_linux.py -------------------------------------------------------------------------------- /ITEM 1-9/ITEM8 training_YOLOv3/OpenImageV4/OpenImages_windows.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM8 training_YOLOv3/OpenImageV4/OpenImages_windows.py -------------------------------------------------------------------------------- /ITEM 1-9/ITEM8 training_YOLOv3/OpenImageV4/README.md: -------------------------------------------------------------------------------- 1 | Training YOLOv3 Object Detector - Snowman 2 | 3 | 1. Install awscli 4 | 5 | `sudo pip3 install awscli` 6 | 7 | 2. Get the relevant OpenImages files needed to locate images of our interest 8 | 9 | `wget https://storage.googleapis.com/openimages/2018_04/class-descriptions-boxable.csv` 10 | 11 | `wget https://storage.googleapis.com/openimages/2018_04/train/train-annotations-bbox.csv` 12 | 13 | 3. Download the images from OpenImagesV4 14 | 15 | `python3 getDataFromOpenImages_snowman.py` 16 | 17 | 4. Create the train-test split 18 | 19 | `python3 splitTrainAndTest.py /data-ssd/sunita/snowman/JPEGImages` 20 | 21 | Give the correct path to the data JPEGImages folder. The 'labels' folder should be in the same directory as the JPEGImages folder. 22 | 23 | 5. Install Darknet and compile it. 24 | ``` 25 | cd ~ 26 | git clone https://github.com/pjreddie/darknet 27 | cd darknet 28 | make 29 | ``` 30 | 6. Get the pretrained model 31 | 32 | `wget https://pjreddie.com/media/files/darknet53.conv.74 -O ~/darknet/darknet53.conv.74` 33 | 34 | 7. Fill in correct paths in the darknet.data file 35 | 36 | 8. Start the training as below, by giving the correct paths to all the files being used as arguments 37 | 38 | `cd ~/darknet` 39 | 40 | `./darknet detector train /path/to/snowman/darknet.data /path/to/snowman/darknet-yolov3.cfg ./darknet53.conv.74 > /path/to/snowman/train.log` 41 | 42 | 9. Give the correct path to the modelConfiguration and modelWeights files in object_detection_yolo.py and test any image or video for snowman detection, e.g. 43 | 44 | `python3 object_detection_yolo.py --image=snowmanImage.jpg` 45 | 46 | -------------------------------------------------------------------------------- /ITEM 1-9/ITEM8 training_YOLOv3/OpenImageV4/splitTrainAndTest.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM8 training_YOLOv3/OpenImageV4/splitTrainAndTest.py -------------------------------------------------------------------------------- /ITEM 1-9/ITEM8 training_YOLOv3/README.md: -------------------------------------------------------------------------------- 1 | Training YOLOv3 Object Detector - Snowman 2 | 3 | 1. Install awscli 4 | 5 | `sudo pip3 install awscli` 6 | 7 | 2. Get the relevant OpenImages files needed to locate images of our interest 8 | 9 | `wget https://storage.googleapis.com/openimages/2018_04/class-descriptions-boxable.csv` 10 | 11 | `wget https://storage.googleapis.com/openimages/2018_04/train/train-annotations-bbox.csv` 12 | 13 | 3. Download the images from OpenImagesV4 14 | 15 | `python3 getDataFromOpenImages_snowman.py` 16 | 17 | 4. Create the train-test split 18 | 19 | `python3 splitTrainAndTest.py /data-ssd/sunita/snowman/JPEGImages` 20 | 21 | Give the correct path to the data JPEGImages folder. The 'labels' folder should be in the same directory as the JPEGImages folder. 22 | 23 | 5. Install Darknet and compile it. 24 | ``` 25 | cd ~ 26 | git clone https://github.com/pjreddie/darknet 27 | cd darknet 28 | make 29 | ``` 30 | 6. Get the pretrained model 31 | 32 | `wget https://pjreddie.com/media/files/darknet53.conv.74 -O ~/darknet/darknet53.conv.74` 33 | 34 | 7. Fill in correct paths in the darknet.data file 35 | 36 | 8. Start the training as below, by giving the correct paths to all the files being used as arguments 37 | 38 | `cd ~/darknet` 39 | 40 | `./darknet detector train /path/to/snowman/darknet.data /path/to/snowman/darknet-yolov3.cfg ./darknet53.conv.74 > /path/to/snowman/train.log` 41 | 42 | 9. Give the correct path to the modelConfiguration and modelWeights files in object_detection_yolo.py and test any image or video for snowman detection, e.g. 43 | 44 | `python3 object_detection_yolo.py --image=snowmanImage.jpg` 45 | 46 | -------------------------------------------------------------------------------- /ITEM 1-9/ITEM8 training_YOLOv3/snowman/classes.names: -------------------------------------------------------------------------------- 1 | snowman 2 | -------------------------------------------------------------------------------- /ITEM 1-9/ITEM8 training_YOLOv3/snowman/darknet.data: -------------------------------------------------------------------------------- 1 | classes = 1 2 | train = /home/your/darknet/snowman/snowman_train.txt 3 | valid = /home/your/darknet/snowman/snowman_test.txt 4 | names = /home/your/darknet/snowman/classes.names 5 | backup = /home/your/darknet/snowman/weights/ 6 | 7 | -------------------------------------------------------------------------------- /ITEM 1-9/ITEM8 training_YOLOv3/snowman/plotTrainLoss.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | log='train.log' 4 | lines = [] 5 | for line in open(log): 6 | if "avg" in line: 7 | lines.append(line) 8 | 9 | iterations = [] 10 | avg_loss = [] 11 | 12 | print('Retrieving data and plotting training loss graph...') 13 | for i in range(len(lines)): 14 | try: 15 | lineParts = lines[i].split(',') 16 | iterations.append(int(lineParts[0].split(':')[0])) 17 | avg_loss.append(float(lineParts[1].split()[0])) 18 | except: 19 | continue 20 | 21 | fig = plt.figure() 22 | for i in range(0, len(lines)): 23 | plt.plot(iterations[i:i+2], avg_loss[i:i+2], 'r.-') 24 | 25 | plt.xlabel('Batch Number') 26 | plt.ylabel('Avg Loss') 27 | fig.savefig('training_loss_plot.png', dpi=300) 28 | 29 | print('Done! Plot saved as training_loss_plot.png') -------------------------------------------------------------------------------- /ITEM 1-9/ITEM9 centroid_blob/image/circle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM9 centroid_blob/image/circle.png -------------------------------------------------------------------------------- /ITEM 1-9/ITEM9 centroid_blob/image/multiple.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 1-9/ITEM9 centroid_blob/image/multiple.png -------------------------------------------------------------------------------- /ITEM 1-9/ITEM9 centroid_blob/multiple_blob.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace cv; 8 | using namespace std; 9 | 10 | RNG rng(12345); 11 | 12 | void find_moments(Mat src); 13 | 14 | int main() 15 | { 16 | String img_path = "./image/multiple.png"; 17 | /// Load source image, convert it to gray 18 | Mat src, gray; 19 | src = imread(img_path); 20 | 21 | cvtColor(src, gray, COLOR_BGR2GRAY); 22 | 23 | //显示原图 24 | namedWindow("Source", WINDOW_AUTOSIZE); 25 | imshow("Source", src); 26 | 27 | // call function to find_moments 寻质心函数 28 | find_moments(gray); 29 | 30 | waitKey(0); 31 | return(0); 32 | } 33 | 34 | void find_moments(Mat gray) 35 | { 36 | Mat canny_output; 37 | //各个轮廓的点集合 38 | vector > contours; 39 | //轮廓输出结果向量 40 | vector hierarchy; 41 | 42 | /// Detect edges using canny 边缘算子提取轮廓 43 | Canny(gray, canny_output, 50, 150, 3); 44 | // Find contours 寻找轮廓 RETR_TREE表示提取所有轮廓 45 | findContours(canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0)); 46 | 47 | /// Get the moments 图像矩 48 | vector mu(contours.size()); 49 | //求取每个轮廓的矩 50 | for (int i = 0; i < contours.size(); i++) 51 | { 52 | mu[i] = moments(contours[i], false); 53 | } 54 | 55 | /// Get the centroid of figures. 轮廓质点 56 | vector mc(contours.size()); 57 | for (int i = 0; i < contours.size(); i++) 58 | { 59 | mc[i] = Point2f(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00); 60 | } 61 | 62 | /// Draw contours 63 | //画轮廓 64 | Mat drawing(canny_output.size(), CV_8UC3, Scalar(255, 255, 255)); 65 | 66 | for (int i = 0; i < contours.size(); i++) 67 | { 68 | Scalar color = Scalar(167, 151, 0); 69 | //画轮廓 70 | drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point()); 71 | //画质心 72 | circle(drawing, mc[i], 4, color, -1, 7, 0); 73 | } 74 | 75 | /// Show the resultant image 76 | namedWindow("Contours", WINDOW_AUTOSIZE); 77 | imshow("Contours", drawing); 78 | waitKey(0); 79 | } -------------------------------------------------------------------------------- /ITEM 1-9/ITEM9 centroid_blob/multiple_blob.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | import cv2 3 | import numpy as np 4 | 5 | 6 | img = cv2.imread('./image/multiple.png') 7 | 8 | # convert the image to grayscale 9 | gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 10 | # convert the grayscale image to binary image 11 | ret,thresh = cv2.threshold(gray_image,127,255,0) 12 | 13 | # find contour in the binary image 14 | contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 15 | for c in contours: 16 | # calculate moments for each contour 17 | M = cv2.moments(c) 18 | cX = int(M["m10"] / M["m00"]) 19 | cY = int(M["m01"] / M["m00"]) 20 | 21 | 22 | # calculate x,y coordinate of center 23 | cv2.circle(img, (cX, cY), 5, (255, 255, 255), -1) 24 | cv2.putText(img, "centroid", (cX - 25, cY - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) 25 | 26 | 27 | # 3.4.1 im2, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) 28 | # 3.2.0 im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 29 | 30 | # display the image 31 | cv2.imshow("Image", img) 32 | cv2.waitKey(0) 33 | -------------------------------------------------------------------------------- /ITEM 1-9/ITEM9 centroid_blob/single_blob.cpp: -------------------------------------------------------------------------------- 1 |  2 | #include "pch.h" 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace cv; 9 | using namespace std; 10 | 11 | 12 | int main() 13 | { 14 | String img_path = "./image/circle.png"; 15 | Mat src, gray, thr; 16 | 17 | src = imread(img_path); 18 | 19 | // convert image to grayscale 获取灰度图 20 | cvtColor(src, gray, COLOR_BGR2GRAY); 21 | 22 | // convert grayscale to binary image 二值化 23 | threshold(gray, thr, 0, 255, THRESH_OTSU); 24 | 25 | // find moments of the image 提取二值图像矩,true表示图像二值化了 26 | Moments m = moments(thr, true); 27 | Point p(m.m10 / m.m00, m.m01 / m.m00); 28 | 29 | // coordinates of centroid 质心坐标 30 | cout << Mat(p) << endl; 31 | 32 | // show the image with a point mark at the centroid 画出质心 33 | circle(src, p, 5, Scalar(128, 0, 0), -1); 34 | imshow("show", src); 35 | waitKey(0); 36 | return 0; 37 | } 38 | 39 | -------------------------------------------------------------------------------- /ITEM 1-9/ITEM9 centroid_blob/single_blob.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | import cv2 3 | import numpy as np 4 | 5 | 6 | # read image through command line 7 | img = cv2.imread('./image/circle.png') 8 | 9 | # convert image to grayscale image 10 | gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 11 | 12 | # convert the grayscale image to binary image 13 | ret,thresh = cv2.threshold(gray_image,127,255,0) 14 | 15 | # calculate moments of binary image 16 | M = cv2.moments(thresh) 17 | 18 | # calculate x,y coordinate of center 19 | cX = int(M["m10"] / M["m00"]) 20 | cY = int(M["m01"] / M["m00"]) 21 | 22 | # put text and highlight the center 23 | cv2.circle(img, (cX, cY), 5, (255, 255, 255), -1) 24 | cv2.putText(img, "centroid", (cX - 25, cY - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) 25 | 26 | # display the image 27 | cv2.imshow("Image", img) 28 | cv2.waitKey(0) 29 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM10 HuMoments/HuMoments.cpp: -------------------------------------------------------------------------------- 1 |  2 | // 3 | 4 | #include "pch.h" 5 | #include 6 | #include "opencv2/opencv.hpp" 7 | 8 | using namespace cv; 9 | using namespace std; 10 | 11 | int main() 12 | { 13 | //是否进行log转换 14 | bool showLogTransformedHuMoments = true; 15 | 16 | // Obtain filename 图像地址 17 | string filename("./image/s0.png"); 18 | 19 | // Read Image 读图 20 | Mat im = imread(filename, IMREAD_GRAYSCALE); 21 | 22 | // Threshold image 阈值分割 23 | threshold(im, im, 0, 255, THRESH_OTSU); 24 | 25 | // Calculate Moments 计算矩 26 | //第二个参数True表示非零的像素都会按值1对待,也就是说相当于对图像进行了二值化处理,阈值为1 27 | Moments moment = moments(im, false); 28 | 29 | // Calculate Hu Moments 计算Hu矩 30 | double huMoments[7]; 31 | HuMoments(moment, huMoments); 32 | 33 | // Print Hu Moments 34 | cout << filename << ": "; 35 | 36 | for (int i = 0; i < 7; i++) 37 | { 38 | if (showLogTransformedHuMoments) 39 | { 40 | // Log transform Hu Moments to make squash the range 41 | cout << -1 * copysign(1.0, huMoments[i]) * log10(abs(huMoments[i])) << " "; 42 | } 43 | else 44 | { 45 | // Hu Moments without log transform. 46 | cout << huMoments[i] << " "; 47 | } 48 | 49 | } 50 | // One row per file 51 | cout << endl; 52 | 53 | } 54 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM10 HuMoments/HuMoments.py: -------------------------------------------------------------------------------- 1 | from math import copysign, log10 2 | 3 | def main(): 4 | showLogTransformedHuMoments = True 5 | 6 | # Obtain filename from command line argument 7 | filename = './image/s0.png' 8 | 9 | # Read image 10 | im = cv2.imread(filename,cv2.IMREAD_GRAYSCALE) 11 | 12 | # Threshold image 13 | _,im = cv2.threshold(im, 128, 255, cv2.THRESH_BINARY) 14 | 15 | # Calculate Moments 16 | moment = cv2.moments(im) 17 | 18 | # Calculate Hu Moments 19 | huMoments = cv2.HuMoments(moment) 20 | 21 | # Print Hu Moments 22 | print("{}: ".format(filename),end='') 23 | 24 | for i in range(0,7): 25 | if showLogTransformedHuMoments: 26 | # Log transform Hu Moments to make 27 | # squash the range 28 | print("{:.5f}".format(-1*copysign(1.0,\ 29 | huMoments[i])*log10(abs(huMoments[i]))),\ 30 | end=' ') 31 | else: 32 | # Hu Moments without log transform 33 | print("{:.5f}".format(huMoments[i]),end=' ') 34 | print() 35 | 36 | if __name__ == "__main__": 37 | main() -------------------------------------------------------------------------------- /ITEM 10-19/ITEM10 HuMoments/image/K0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM10 HuMoments/image/K0.png -------------------------------------------------------------------------------- /ITEM 10-19/ITEM10 HuMoments/image/S0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM10 HuMoments/image/S0.png -------------------------------------------------------------------------------- /ITEM 10-19/ITEM10 HuMoments/image/S1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM10 HuMoments/image/S1.png -------------------------------------------------------------------------------- /ITEM 10-19/ITEM10 HuMoments/image/S2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM10 HuMoments/image/S2.png -------------------------------------------------------------------------------- /ITEM 10-19/ITEM10 HuMoments/image/S3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM10 HuMoments/image/S3.png -------------------------------------------------------------------------------- /ITEM 10-19/ITEM10 HuMoments/image/S4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM10 HuMoments/image/S4.png -------------------------------------------------------------------------------- /ITEM 10-19/ITEM10 HuMoments/image/S5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM10 HuMoments/image/S5.png -------------------------------------------------------------------------------- /ITEM 10-19/ITEM10 HuMoments/shapeMatcher.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "opencv2/opencv.hpp" 3 | 4 | using namespace cv; 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | Mat im1 = imread("./image/S0.png",IMREAD_GRAYSCALE); 10 | Mat im2 = imread("./image/K0.png",IMREAD_GRAYSCALE); 11 | Mat im3 = imread("./image/S4.png",IMREAD_GRAYSCALE); 12 | 13 | double m1 = matchShapes(im1, im1, CONTOURS_MATCH_I2, 0); 14 | double m2 = matchShapes(im1, im2, CONTOURS_MATCH_I2, 0); 15 | double m3 = matchShapes(im1, im3, CONTOURS_MATCH_I2, 0); 16 | 17 | cout << "Shape Distances Between " << endl << "-------------------------" << endl; 18 | cout << "S0.png and S0.png : " << m1 << endl; 19 | cout << "S0.png and K0.png : " << m2 << endl; 20 | cout << "S0.png and S4.png : " << m3 << endl; 21 | } 22 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM10 HuMoments/shapeMatcher.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | def main(): 4 | 5 | im1 = cv2.imread("./image/S0.png",cv2.IMREAD_GRAYSCALE) 6 | im2 = cv2.imread("./image/K0.png",cv2.IMREAD_GRAYSCALE) 7 | im3 = cv2.imread("./images/S4.png",cv2.IMREAD_GRAYSCALE) 8 | 9 | m1 = cv2.matchShapes(im1,im1,cv2.CONTOURS_MATCH_I2,0) 10 | m2 = cv2.matchShapes(im1,im2,cv2.CONTOURS_MATCH_I2,0) 11 | m3 = cv2.matchShapes(im1,im3,cv2.CONTOURS_MATCH_I2,0) 12 | 13 | print("Shape Distances Between \n-------------------------") 14 | 15 | print("S0.png and S0.png : {}".format(m1)) 16 | print("S0.png and K0.png : {}".format(m2)) 17 | print("S0.png and S4.png : {}".format(m3)) 18 | 19 | if __name__ == "__main__": 20 | main() 21 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM11 QRCode_scanner/Image/demo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM11 QRCode_scanner/Image/demo.jpg -------------------------------------------------------------------------------- /ITEM 10-19/ITEM11 QRCode_scanner/QRCode_scanner.cpp: -------------------------------------------------------------------------------- 1 | // QRCode_scanner.cpp 2 | 3 | #include "pch.h" 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace cv; 9 | using namespace std; 10 | 11 | /** 12 | * @brief 用于显示检测到的QR码周围的框 13 | * 14 | * @param im 15 | * @param bbox 16 | */ 17 | void display(Mat &im, Mat &bbox) 18 | { 19 | int n = bbox.rows; 20 | for (int i = 0; i < n; i++) 21 | { 22 | line(im, Point2i(bbox.at(i, 0), bbox.at(i, 1)), 23 | Point2i(bbox.at((i + 1) % n, 0), bbox.at((i + 1) % n, 1)), Scalar(255, 0, 0), 3); 24 | } 25 | imshow("Result", im); 26 | } 27 | 28 | int main() 29 | { 30 | // Read image 31 | Mat inputImage = imread("./image/demo.jpg"); 32 | 33 | //QR检测器 34 | QRCodeDetector qrDecoder = QRCodeDetector::QRCodeDetector(); 35 | 36 | //二维码边框坐标,提取出来的二维码 37 | Mat bbox, rectifiedImage; 38 | 39 | //检测二维码 40 | std::string data = qrDecoder.detectAndDecode(inputImage, bbox, rectifiedImage); 41 | 42 | //获取二维码中的数据链接 43 | if (data.length() > 0) 44 | { 45 | cout << "Decoded Data : " << data << endl; 46 | display(inputImage, bbox); 47 | rectifiedImage.convertTo(rectifiedImage, CV_8UC3); 48 | //展示二维码 49 | imshow("Rectified QRCode", rectifiedImage); 50 | 51 | waitKey(0); 52 | } 53 | else 54 | { 55 | cout << "QR Code not detected" << endl; 56 | } 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM11 QRCode_scanner/QRCode_scanner.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import time 4 | 5 | 6 | inputImage = cv2.imread("./image/demo.jpg") 7 | 8 | # Display barcode and QR code location 9 | def display(im, bbox): 10 | n = len(bbox) 11 | for j in range(n): 12 | cv2.line(im, tuple(bbox[j][0]), tuple(bbox[ (j+1) % n][0]), (255,0,0), 3) 13 | 14 | # Display results 15 | cv2.imshow("Results", im) 16 | 17 | # Create a qrCodeDetector Object 18 | qrDecoder = cv2.QRCodeDetector() 19 | 20 | # Detect and decode the qrcode 21 | t = time.time() 22 | data,bbox,rectifiedImage = qrDecoder.detectAndDecode(inputImage) 23 | print("Time Taken for Detect and Decode : {:.3f} seconds".format(time.time() - t)) 24 | if len(data)>0: 25 | print("Decoded Data : {}".format(data)) 26 | display(inputImage, bbox) 27 | rectifiedImage = np.uint8(rectifiedImage); 28 | cv2.imshow("Rectified QRCode", rectifiedImage); 29 | else: 30 | print("QR Code not detected") 31 | cv2.imshow("Results", inputImage) 32 | cv2.imwrite("output.jpg",inputImage) 33 | cv2.waitKey(0) 34 | cv2.destroyAllWindows() 35 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM12 HandPoints_detection/handPoseImage.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import cv2 3 | import time 4 | import numpy as np 5 | 6 | protoFile = "./model/pose_deploy.prototxt" 7 | weightsFile = "./model/pose_iter_102000.caffemodel" 8 | nPoints = 22 9 | POSE_PAIRS = [ [0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[0,9],[9,10],[10,11],[11,12],[0,13],[13,14],[14,15],[15,16],[0,17],[17,18],[18,19],[19,20] ] 10 | net = cv2.dnn.readNetFromCaffe(protoFile, weightsFile) 11 | 12 | frame = cv2.imread("./image/hand.jpg") 13 | frameCopy = np.copy(frame) 14 | frameWidth = frame.shape[1] 15 | frameHeight = frame.shape[0] 16 | aspect_ratio = frameWidth/frameHeight 17 | 18 | threshold = 0.1 19 | 20 | t = time.time() 21 | # input image dimensions for the network 22 | inHeight = 368 23 | inWidth = int(((aspect_ratio*inHeight)*8)//8) 24 | inpBlob = cv2.dnn.blobFromImage(frame, 1.0 / 255, (inWidth, inHeight), (0, 0, 0), swapRB=False, crop=False) 25 | 26 | net.setInput(inpBlob) 27 | 28 | output = net.forward() 29 | print("time taken by network : {:.3f}".format(time.time() - t)) 30 | 31 | # Empty list to store the detected keypoints 32 | points = [] 33 | 34 | for i in range(nPoints): 35 | # confidence map of corresponding body's part. 36 | probMap = output[0, i, :, :] 37 | probMap = cv2.resize(probMap, (frameWidth, frameHeight)) 38 | 39 | # Find global maxima of the probMap. 40 | minVal, prob, minLoc, point = cv2.minMaxLoc(probMap) 41 | 42 | if prob > threshold : 43 | cv2.circle(frameCopy, (int(point[0]), int(point[1])), 8, (0, 255, 255), thickness=-1, lineType=cv2.FILLED) 44 | cv2.putText(frameCopy, "{}".format(i), (int(point[0]), int(point[1])), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, lineType=cv2.LINE_AA) 45 | 46 | # Add the point to the list if the probability is greater than the threshold 47 | points.append((int(point[0]), int(point[1]))) 48 | else : 49 | points.append(None) 50 | 51 | # Draw Skeleton 52 | for pair in POSE_PAIRS: 53 | partA = pair[0] 54 | partB = pair[1] 55 | 56 | if points[partA] and points[partB]: 57 | cv2.line(frame, points[partA], points[partB], (0, 255, 255), 2) 58 | cv2.circle(frame, points[partA], 8, (0, 0, 255), thickness=-1, lineType=cv2.FILLED) 59 | cv2.circle(frame, points[partB], 8, (0, 0, 255), thickness=-1, lineType=cv2.FILLED) 60 | 61 | 62 | cv2.imshow('Output-Keypoints', frameCopy) 63 | cv2.imshow('Output-Skeleton', frame) 64 | 65 | 66 | cv2.imwrite('Output-Keypoints.jpg', frameCopy) 67 | cv2.imwrite('Output-Skeleton.jpg', frame) 68 | 69 | print("Total time taken : {:.3f}".format(time.time() - t)) 70 | 71 | cv2.waitKey(0) 72 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM12 HandPoints_detection/image/hand.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM12 HandPoints_detection/image/hand.jpg -------------------------------------------------------------------------------- /ITEM 10-19/ITEM12 HandPoints_detection/image/hand_other.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM12 HandPoints_detection/image/hand_other.jpg -------------------------------------------------------------------------------- /ITEM 10-19/ITEM12 HandPoints_detection/model/getModels.sh: -------------------------------------------------------------------------------- 1 | # ------------------------- BODY, FACE AND HAND MODELS ------------------------- 2 | # Downloading body pose (COCO and MPI), face and hand models 3 | OPENPOSE_URL="http://posefs1.perception.cs.cmu.edu/OpenPose/models/" 4 | HAND_FOLDER="hand/" 5 | 6 | # "------------------------- HAND MODELS -------------------------" 7 | # Hand 8 | HAND_MODEL=$HAND_FOLDER"pose_iter_102000.caffemodel" 9 | wget -c ${OPENPOSE_URL}${HAND_MODEL} -P ${HAND_FOLDER} 10 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM13 Mask R-CNN in OpenCV/image/cars.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM13 Mask R-CNN in OpenCV/image/cars.jpg -------------------------------------------------------------------------------- /ITEM 10-19/ITEM13 Mask R-CNN in OpenCV/model/colors.txt: -------------------------------------------------------------------------------- 1 | 0 255 0 2 | 0 0 255 3 | 255 0 0 4 | 0 255 255 5 | 255 255 0 6 | 255 0 255 7 | 80 70 180 8 | 250 80 190 9 | 245 145 50 10 | 70 150 250 11 | 50 190 190 12 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM13 Mask R-CNN in OpenCV/model/mscoco_labels.names: -------------------------------------------------------------------------------- 1 | person 2 | bicycle 3 | car 4 | motorcycle 5 | airplane 6 | bus 7 | train 8 | truck 9 | boat 10 | traffic light 11 | fire hydrant 12 | 13 | stop sign 14 | parking meter 15 | bench 16 | bird 17 | cat 18 | dog 19 | horse 20 | sheep 21 | cow 22 | elephant 23 | bear 24 | zebra 25 | giraffe 26 | 27 | backpack 28 | umbrella 29 | 30 | 31 | handbag 32 | tie 33 | suitcase 34 | frisbee 35 | skis 36 | snowboard 37 | sports ball 38 | kite 39 | baseball bat 40 | baseball glove 41 | skateboard 42 | surfboard 43 | tennis racket 44 | bottle 45 | 46 | wine glass 47 | cup 48 | fork 49 | knife 50 | spoon 51 | bowl 52 | banana 53 | apple 54 | sandwich 55 | orange 56 | broccoli 57 | carrot 58 | hot dog 59 | pizza 60 | donut 61 | cake 62 | chair 63 | couch 64 | potted plant 65 | bed 66 | 67 | dining table 68 | 69 | 70 | toilet 71 | 72 | tv 73 | laptop 74 | mouse 75 | remote 76 | keyboard 77 | cell phone 78 | microwave 79 | oven 80 | toaster 81 | sink 82 | refrigerator 83 | 84 | book 85 | clock 86 | vase 87 | scissors 88 | teddy bear 89 | hair drier 90 | toothbrush 91 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM14 Opencv_SingleTracker/video/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/luohenyueji/OpenCV-ML-Model/blob/master/OpenCV-Practical-Exercise-Model/videos/chaplin.zip -------------------------------------------------------------------------------- /ITEM 10-19/ITEM15 GOTURN_SingleTracker/GOTURN_SingleTracker.cpp: -------------------------------------------------------------------------------- 1 | // GOTURN_SingleTracker.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 2 | // 3 | 4 | #include "pch.h" 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace cv; 10 | using namespace std; 11 | 12 | int main() 13 | { 14 | // Create tracker 15 | Ptr tracker = TrackerGOTURN::create(); 16 | 17 | // Read video 18 | VideoCapture video("video/chaplin.mp4"); 19 | 20 | // Exit if video is not opened 21 | if (!video.isOpened()) 22 | { 23 | cout << "Could not read video file" << endl; 24 | return EXIT_FAILURE; 25 | } 26 | 27 | // Read first frame 28 | Mat frame; 29 | if (!video.read(frame)) 30 | { 31 | cout << "Cannot read video file" << endl; 32 | return EXIT_FAILURE; 33 | } 34 | 35 | // Define initial boundibg box 36 | Rect2d bbox(287, 23, 86, 320); 37 | 38 | // Uncomment the line below to select a different bounding box 39 | //bbox = selectROI(frame, false); 40 | 41 | // Initialize tracker with first frame and bounding box 42 | tracker->init(frame, bbox); 43 | 44 | while (video.read(frame)) 45 | { 46 | // Start timer 47 | double timer = (double)getTickCount(); 48 | 49 | // Update the tracking result 50 | bool ok = tracker->update(frame, bbox); 51 | 52 | // Calculate Frames per second (FPS) 53 | float fps = getTickFrequency() / ((double)getTickCount() - timer); 54 | 55 | if (ok) 56 | { 57 | // Tracking success : Draw the tracked object 58 | rectangle(frame, bbox, Scalar(255, 0, 0), 2, 1); 59 | } 60 | else 61 | { 62 | // Tracking failure detected. 63 | putText(frame, "Tracking failure detected", Point(100, 80), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 0, 255), 2); 64 | } 65 | 66 | // Display tracker type on frame 67 | putText(frame, "GOTURN Tracker", Point(100, 20), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(50, 170, 50), 2); 68 | 69 | // Display FPS on frame 70 | putText(frame, "FPS : " + to_string(int(fps)), Point(100, 50), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(50, 170, 50), 2); 71 | // Display frame. 72 | imshow("Tracking", frame); 73 | 74 | // Exit if ESC pressed. 75 | if (waitKey(1) == 27) break; 76 | } 77 | 78 | return 0; 79 | } -------------------------------------------------------------------------------- /ITEM 10-19/ITEM15 GOTURN_SingleTracker/GOTURN_SingleTracker.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Import modules 4 | import cv2, sys, os 5 | 6 | if not (os.path.isfile('goturn.caffemodel') and os.path.isfile('goturn.prototxt')): 7 | errorMsg = ''' 8 | Could not find GOTURN model in current directory. 9 | Please ensure goturn.caffemodel and goturn.prototxt are in the current directory 10 | ''' 11 | 12 | print(errorMsg) 13 | sys.exit() 14 | 15 | # Create tracker 16 | tracker = cv2.TrackerGOTURN_create() 17 | 18 | # Read video 19 | video = cv2.VideoCapture("chaplin.mp4") 20 | 21 | # Exit if video not opened 22 | if not video.isOpened(): 23 | print("Could not open video") 24 | sys.exit() 25 | 26 | # Read first frame 27 | ok,frame = video.read() 28 | if not ok: 29 | print("Cannot read video file") 30 | sys.exit() 31 | 32 | 33 | # Define a bounding box 34 | bbox = (276, 23, 86, 320) 35 | 36 | # Uncomment the line below to select a different bounding box 37 | bbox = cv2.selectROI(frame, False) 38 | 39 | # Initialize tracker with first frame and bounding box 40 | ok = tracker.init(frame,bbox) 41 | 42 | while True: 43 | # Read a new frame 44 | ok, frame = video.read() 45 | if not ok: 46 | break 47 | 48 | # Start timer 49 | timer = cv2.getTickCount() 50 | 51 | # Update tracker 52 | ok, bbox = tracker.update(frame) 53 | 54 | # Calculate Frames per second (FPS) 55 | fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer); 56 | 57 | # Draw bounding box 58 | if ok: 59 | # Tracking success 60 | p1 = (int(bbox[0]), int(bbox[1])) 61 | p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3])) 62 | cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1) 63 | else : 64 | # Tracking failure 65 | cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2) 66 | 67 | # Display tracker type on frame 68 | cv2.putText(frame, "GOTURN Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2); 69 | 70 | # Display FPS on frame 71 | cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2); 72 | 73 | # Display result 74 | cv2.imshow("Tracking", frame) 75 | 76 | # Exit if ESC pressed 77 | k = cv2.waitKey(1) & 0xff 78 | if k == 27: 79 | break 80 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM15 GOTURN_SingleTracker/video/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/luohenyueji/OpenCV-ML-Model/blob/master/OpenCV-Practical-Exercise-Model/videos/chaplin.zip -------------------------------------------------------------------------------- /ITEM 10-19/ITEM16 OpenCV_MultiTracker/video/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/luohenyueji/OpenCV-ML-Model/blob/master/OpenCV-Practical-Exercise-Model/videos/16run.zip -------------------------------------------------------------------------------- /ITEM 10-19/ITEM17 OpenCV_Colorization/OpenCV_ImageColorization.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import numpy as np 4 | import cv2 as cv 5 | 6 | # Read the input image 7 | frame = cv.imread("./image/greyscaleImage.png") 8 | 9 | # Specify the paths for the 2 model files 10 | protoFile = "./model/colorization_deploy_v2.prototxt" 11 | weightsFile = "./model/colorization_release_v2.caffemodel" 12 | #weightsFile = "./model/colorization_release_v2_norebal.caffemodel" 13 | 14 | # Load the cluster centers 15 | pts_in_hull = np.load('./model/pts_in_hull.npy') 16 | 17 | # Read the network into Memory 18 | net = cv.dnn.readNetFromCaffe(protoFile, weightsFile) 19 | 20 | # populate cluster centers as 1x1 convolution kernel 21 | pts_in_hull = pts_in_hull.transpose().reshape(2, 313, 1, 1) 22 | net.getLayer(net.getLayerId('class8_ab')).blobs = [pts_in_hull.astype(np.float32)] 23 | net.getLayer(net.getLayerId('conv8_313_rh')).blobs = [np.full([1, 313], 2.606, np.float32)] 24 | 25 | #from opencv sample 26 | W_in = 224 27 | H_in = 224 28 | 29 | img_rgb = (frame[:,:,[2, 1, 0]] * 1.0 / 255).astype(np.float32) 30 | img_lab = cv.cvtColor(img_rgb, cv.COLOR_RGB2Lab) 31 | img_l = img_lab[:,:,0] # pull out L channel 32 | 33 | # resize lightness channel to network input size 34 | img_l_rs = cv.resize(img_l, (W_in, H_in)) # 35 | img_l_rs -= 50 # subtract 50 for mean-centering 36 | 37 | net.setInput(cv.dnn.blobFromImage(img_l_rs)) 38 | ab_dec = net.forward()[0,:,:,:].transpose((1,2,0)) # this is our result 39 | 40 | (H_orig,W_orig) = img_rgb.shape[:2] # original image size 41 | ab_dec_us = cv.resize(ab_dec, (W_orig, H_orig)) 42 | img_lab_out = np.concatenate((img_l[:,:,np.newaxis],ab_dec_us),axis=2) # concatenate with original image L 43 | img_bgr_out = np.clip(cv.cvtColor(img_lab_out, cv.COLOR_Lab2BGR), 0, 1) 44 | 45 | outputFile = '_colorized.png' 46 | cv.imwrite(outputFile, (img_bgr_out*255).astype(np.uint8)) 47 | print('Colorized image saved as '+outputFile) 48 | print('Done !!!') 49 | 50 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM17 OpenCV_Colorization/OpenCV_VideoColorization.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import cv2 as cv 4 | import argparse 5 | import os.path 6 | 7 | 8 | # Read the input video 9 | cap = cv.VideoCapture('video/greyscaleVideo.mp4') 10 | hasFrame, frame = cap.read() 11 | 12 | outputFile = 'colorized.avi' 13 | vid_writer = cv.VideoWriter(outputFile, cv.VideoWriter_fourcc('M','J','P','G'), 60, (frame.shape[1],frame.shape[0])) 14 | 15 | # Specify the paths for the 2 model files 16 | protoFile = "./model/colorization_deploy_v2.prototxt" 17 | #weightsFile = "./model/colorization_release_v2.caffemodel" 18 | weightsFile = "./model/colorization_release_v2_norebal.caffemodel" 19 | 20 | # Load the cluster centers 21 | pts_in_hull = np.load('./model/pts_in_hull.npy') 22 | 23 | # Read the network into Memory 24 | net = cv.dnn.readNetFromCaffe(protoFile, weightsFile) 25 | 26 | # populate cluster centers as 1x1 convolution kernel 27 | pts_in_hull = pts_in_hull.transpose().reshape(2, 313, 1, 1) 28 | net.getLayer(net.getLayerId('class8_ab')).blobs = [pts_in_hull.astype(np.float32)] 29 | net.getLayer(net.getLayerId('conv8_313_rh')).blobs = [np.full([1, 313], 2.606, np.float32)] 30 | 31 | #from opencv sample 32 | W_in = 224 33 | H_in = 224 34 | 35 | i=0 36 | while cv.waitKey(1): 37 | 38 | hasFrame, frame = cap.read() 39 | frameCopy = np.copy(frame) 40 | if not hasFrame: 41 | break 42 | 43 | img_rgb = (frame[:,:,[2, 1, 0]] * 1.0 / 255).astype(np.float32) 44 | img_lab = cv.cvtColor(img_rgb, cv.COLOR_RGB2Lab) 45 | img_l = img_lab[:,:,0] # pull out L channel 46 | 47 | # resize lightness channel to network input size 48 | img_l_rs = cv.resize(img_l, (W_in, H_in)) 49 | img_l_rs -= 50 # subtract 50 for mean-centering 50 | 51 | net.setInput(cv.dnn.blobFromImage(img_l_rs)) 52 | ab_dec = net.forward()[0,:,:,:].transpose((1,2,0)) # this is our result 53 | 54 | (H_orig,W_orig) = img_rgb.shape[:2] # original image size 55 | ab_dec_us = cv.resize(ab_dec, (W_orig, H_orig)) 56 | img_lab_out = np.concatenate((img_l[:,:,np.newaxis],ab_dec_us),axis=2) # concatenate with original L channel 57 | img_bgr_out = np.clip(cv.cvtColor(img_lab_out, cv.COLOR_Lab2BGR), 0, 1) 58 | 59 | vid_writer.write((img_bgr_out*255).astype(np.uint8)) 60 | i +=1 61 | print("the current frame is: {}th".format(i)) 62 | vid_writer.release() 63 | 64 | print('Colorized video saved as '+outputFile) 65 | print('Done !!!') 66 | 67 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM17 OpenCV_Colorization/image/greyscaleImage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM17 OpenCV_Colorization/image/greyscaleImage.png -------------------------------------------------------------------------------- /ITEM 10-19/ITEM17 OpenCV_Colorization/model/pts_in_hull.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM17 OpenCV_Colorization/model/pts_in_hull.npy -------------------------------------------------------------------------------- /ITEM 10-19/ITEM17 OpenCV_Colorization/video/greyscaleVideo.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM17 OpenCV_Colorization/video/greyscaleVideo.mp4 -------------------------------------------------------------------------------- /ITEM 10-19/ITEM18 OpenCV_Homography/OpenCV_Homography.cpp: -------------------------------------------------------------------------------- 1 | // OpenCV_Homography.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 2 | // 3 | 4 | #include "pch.h" 5 | #include 6 | #include 7 | 8 | using namespace cv; 9 | using namespace std; 10 | 11 | 12 | 13 | int main(int argc, char** argv) 14 | { 15 | // Read source image 原图 16 | Mat im_src = imread("./image/book2.jpg"); 17 | // Four corners of the book in source image 4个角点 18 | vector pts_src; 19 | pts_src.push_back(Point2f(141, 131)); 20 | pts_src.push_back(Point2f(480, 159)); 21 | pts_src.push_back(Point2f(493, 630)); 22 | pts_src.push_back(Point2f(64, 601)); 23 | 24 | 25 | // Read destination image.目标图 26 | Mat im_dst = imread("./image/book1.jpg"); 27 | 28 | // Four corners of the book in destination image. 4个对应点 29 | vector pts_dst; 30 | pts_dst.push_back(Point2f(318, 256)); 31 | pts_dst.push_back(Point2f(534, 372)); 32 | pts_dst.push_back(Point2f(316, 670)); 33 | pts_dst.push_back(Point2f(73, 473)); 34 | 35 | // Calculate Homography 计算Homography需要至少4组对应点. 36 | // pts_src : 源图像点坐标,pts_dst : 结果图像坐标 37 | Mat h = findHomography(pts_src, pts_dst); 38 | 39 | // Output image 40 | Mat im_out; 41 | // Warp source image to destination based on homography 仿射变换 42 | warpPerspective(im_src, im_out, h, im_dst.size()); 43 | 44 | // Display images 45 | imshow("Source Image", im_src); 46 | imshow("Destination Image", im_dst); 47 | imshow("Warped Source Image", im_out); 48 | 49 | waitKey(0); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /ITEM 10-19/ITEM18 OpenCV_Homography/OpenCV_Homography.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2 4 | import numpy as np 5 | 6 | if __name__ == '__main__' : 7 | 8 | # Read source image. 9 | im_src = cv2.imread('./image/book2.jpg') 10 | # Four corners of the book in source image 11 | pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]]) 12 | 13 | 14 | # Read destination image. 15 | im_dst = cv2.imread('./image/book1.jpg') 16 | # Four corners of the book in destination image. 17 | pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]]) 18 | 19 | # Calculate Homography 20 | h, status = cv2.findHomography(pts_src, pts_dst) 21 | 22 | # Warp source image to destination based on homography 23 | im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0])) 24 | 25 | # Display images 26 | cv2.imshow("Source Image", im_src) 27 | cv2.imshow("Destination Image", im_dst) 28 | cv2.imshow("Warped Source Image", im_out) 29 | 30 | cv2.waitKey(0) -------------------------------------------------------------------------------- /ITEM 10-19/ITEM18 OpenCV_Homography/image/book1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM18 OpenCV_Homography/image/book1.jpg -------------------------------------------------------------------------------- /ITEM 10-19/ITEM18 OpenCV_Homography/image/book2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM18 OpenCV_Homography/image/book2.jpg -------------------------------------------------------------------------------- /ITEM 10-19/ITEM18 OpenCV_Homography/virtual-billboard/first-image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM18 OpenCV_Homography/virtual-billboard/first-image.jpg -------------------------------------------------------------------------------- /ITEM 10-19/ITEM18 OpenCV_Homography/virtual-billboard/times-square.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM18 OpenCV_Homography/virtual-billboard/times-square.jpg -------------------------------------------------------------------------------- /ITEM 10-19/ITEM18 OpenCV_Homography/virtual-billboard/utils.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | def mouse_handler(event, x, y, flags, data) : 5 | 6 | if event == cv2.EVENT_LBUTTONDOWN : 7 | cv2.circle(data['im'], (x,y),3, (0,0,255), 5, 16); 8 | cv2.imshow("Image", data['im']); 9 | if len(data['points']) < 4 : 10 | data['points'].append([x,y]) 11 | 12 | def get_four_points(im): 13 | 14 | # Set up data to send to mouse handler 15 | data = {} 16 | data['im'] = im.copy() 17 | data['points'] = [] 18 | 19 | #Set the callback function for any mouse event 20 | cv2.imshow("Image",im) 21 | cv2.setMouseCallback("Image", mouse_handler, data) 22 | cv2.waitKey(0) 23 | 24 | # Convert array to np.array 25 | points = np.vstack(data['points']).astype(float) 26 | 27 | return points 28 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM18 OpenCV_Homography/virtual-billboard/virtual-billboard.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace cv; 4 | using namespace std; 5 | 6 | struct userdata{ 7 | Mat im; 8 | vector points; 9 | }; 10 | 11 | 12 | void mouseHandler(int event, int x, int y, int flags, void* data_ptr) 13 | { 14 | if ( event == EVENT_LBUTTONDOWN ) 15 | { 16 | userdata *data = ((userdata *) data_ptr); 17 | circle(data->im, Point(x,y),3,Scalar(0,255,255), 5, CV_AA); 18 | imshow("Image", data->im); 19 | if (data->points.size() < 4) 20 | { 21 | data->points.push_back(Point2f(x,y)); 22 | } 23 | } 24 | 25 | } 26 | 27 | 28 | 29 | int main( int argc, char** argv) 30 | { 31 | 32 | // Read in the image. 33 | Mat im_src = imread("first-image.jpg"); 34 | Size size = im_src.size(); 35 | 36 | // Create a vector of points. 37 | vector pts_src; 38 | pts_src.push_back(Point2f(0,0)); 39 | pts_src.push_back(Point2f(size.width - 1, 0)); 40 | pts_src.push_back(Point2f(size.width - 1, size.height -1)); 41 | pts_src.push_back(Point2f(0, size.height - 1 )); 42 | 43 | 44 | 45 | // Destination image 46 | Mat im_dst = imread("times-square.jpg"); 47 | 48 | 49 | // Set data for mouse handler 50 | Mat im_temp = im_dst.clone(); 51 | userdata data; 52 | data.im = im_temp; 53 | 54 | 55 | //show the image 56 | imshow("Image", im_temp); 57 | 58 | cout << "Click on four corners of a billboard and then press ENTER" << endl; 59 | //set the callback function for any mouse event 60 | setMouseCallback("Image", mouseHandler, &data); 61 | waitKey(0); 62 | 63 | // Calculate Homography between source and destination points 64 | Mat h = findHomography(pts_src, data.points); 65 | 66 | // Warp source image 67 | warpPerspective(im_src, im_temp, h, im_temp.size()); 68 | 69 | // Extract four points from mouse data 70 | Point pts_dst[4]; 71 | for( int i = 0; i < 4; i++) 72 | { 73 | pts_dst[i] = data.points[i]; 74 | } 75 | 76 | // Black out polygonal area in destination image. 77 | fillConvexPoly(im_dst, pts_dst, 4, Scalar(0), CV_AA); 78 | 79 | // Add warped source image to destination image. 80 | im_dst = im_dst + im_temp; 81 | 82 | // Display image. 83 | imshow("Image", im_dst); 84 | waitKey(0); 85 | 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM18 OpenCV_Homography/virtual-billboard/virtual-billboard.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2 4 | import numpy as np 5 | from utils import mouse_handler 6 | from utils import get_four_points 7 | import sys 8 | 9 | 10 | if __name__ == '__main__' : 11 | 12 | # Read source image. 13 | im_src = cv2.imread('first-image.jpg'); 14 | size = im_src.shape 15 | 16 | # Create a vector of source points. 17 | pts_src = np.array( 18 | [ 19 | [0,0], 20 | [size[1] - 1, 0], 21 | [size[1] - 1, size[0] -1], 22 | [0, size[0] - 1 ] 23 | ],dtype=float 24 | ); 25 | 26 | 27 | # Read destination image 28 | im_dst = cv2.imread('times-square.jpg'); 29 | 30 | # Get four corners of the billboard 31 | print('Click on four corners of a billboard and then press ENTER') 32 | pts_dst = get_four_points(im_dst) 33 | 34 | # Calculate Homography between source and destination points 35 | h, status = cv2.findHomography(pts_src, pts_dst); 36 | 37 | # Warp source image 38 | im_temp = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0])) 39 | 40 | # Black out polygonal area in destination image. 41 | cv2.fillConvexPoly(im_dst, pts_dst.astype(int), 0, 16); 42 | 43 | # Add warped source image to destination image. 44 | im_dst = im_dst + im_temp; 45 | 46 | # Display image. 47 | cv2.imshow("Image", im_dst); 48 | cv2.waitKey(0); 49 | 50 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM19 OpenCV_Align/OpenCV_Align.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import cv2 3 | import numpy as np 4 | 5 | 6 | MAX_MATCHES = 500 7 | GOOD_MATCH_PERCENT = 0.15 8 | 9 | 10 | def alignImages(im1, im2): 11 | 12 | # Convert images to grayscale 13 | im1Gray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY) 14 | im2Gray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY) 15 | 16 | # Detect ORB features and compute descriptors. 17 | orb = cv2.ORB_create(MAX_MATCHES) 18 | keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None) 19 | keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None) 20 | 21 | # Match features. 22 | matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING) 23 | matches = matcher.match(descriptors1, descriptors2, None) 24 | 25 | # Sort matches by score 26 | matches.sort(key=lambda x: x.distance, reverse=False) 27 | 28 | # Remove not so good matches 29 | numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT) 30 | matches = matches[:numGoodMatches] 31 | 32 | # Draw top matches 33 | imMatches = cv2.drawMatches(im1, keypoints1, im2, keypoints2, matches, None) 34 | cv2.imwrite("matches.jpg", imMatches) 35 | 36 | # Extract location of good matches 37 | points1 = np.zeros((len(matches), 2), dtype=np.float32) 38 | points2 = np.zeros((len(matches), 2), dtype=np.float32) 39 | 40 | for i, match in enumerate(matches): 41 | points1[i, :] = keypoints1[match.queryIdx].pt 42 | points2[i, :] = keypoints2[match.trainIdx].pt 43 | 44 | # Find homography 45 | h, mask = cv2.findHomography(points1, points2, cv2.RANSAC) 46 | 47 | # Use homography 48 | height, width, channels = im2.shape 49 | im1Reg = cv2.warpPerspective(im1, h, (width, height)) 50 | 51 | return im1Reg, h 52 | 53 | 54 | if __name__ == '__main__': 55 | 56 | # Read reference image 57 | refFilename = "./image/form.jpg" 58 | print("Reading reference image : ", refFilename) 59 | imReference = cv2.imread(refFilename, cv2.IMREAD_COLOR) 60 | 61 | # Read image to be aligned 62 | imFilename = "./image/scanned-form.jpg" 63 | print("Reading image to align : ", imFilename); 64 | im = cv2.imread(imFilename, cv2.IMREAD_COLOR) 65 | 66 | print("Aligning images ...") 67 | # Registered image will be resotred in imReg. 68 | # The estimated homography will be stored in h. 69 | imReg, h = alignImages(im, imReference) 70 | 71 | # Write aligned image to disk. 72 | outFilename = "aligned.jpg" 73 | print("Saving aligned image : ", outFilename); 74 | cv2.imwrite(outFilename, imReg) 75 | 76 | # Print estimated homography 77 | print("Estimated homography : \n", h) 78 | 79 | -------------------------------------------------------------------------------- /ITEM 10-19/ITEM19 OpenCV_Align/image/form.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM19 OpenCV_Align/image/form.jpg -------------------------------------------------------------------------------- /ITEM 10-19/ITEM19 OpenCV_Align/image/scanned-form.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 10-19/ITEM19 OpenCV_Align/image/scanned-form.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM20 OpenCV_ECCAlignment/OpenCV_ECCAlignment.py: -------------------------------------------------------------------------------- 1 |  2 | import cv2 3 | import numpy as np 4 | 5 | def get_gradient(im) : 6 | # Calculate the x and y gradients using Sobel operator 7 | grad_x = cv2.Sobel(im,cv2.CV_32F,1,0,ksize=3) 8 | grad_y = cv2.Sobel(im,cv2.CV_32F,0,1,ksize=3) 9 | # Combine the two gradients 10 | grad = cv2.addWeighted(np.absolute(grad_x), 0.5, np.absolute(grad_y), 0.5, 0) 11 | return grad 12 | 13 | 14 | if __name__ == '__main__': 15 | 16 | 17 | # Read 8-bit color image. 18 | # This is an image in which the three channels are 19 | # concatenated vertically. 20 | 21 | im = cv2.imread("image/girls.jpg", cv2.IMREAD_GRAYSCALE); 22 | 23 | # Find the width and height of the color image 24 | sz = im.shape 25 | print(sz) 26 | height = int(sz[0] / 3); 27 | width = sz[1] 28 | 29 | # Extract the three channels from the gray scale image 30 | # and merge the three channels into one color image 31 | im_color = np.zeros((height,width,3), dtype=np.uint8 ) 32 | for i in range(0,3) : 33 | im_color[:,:,i] = im[ i * height:(i+1) * height,:] 34 | 35 | # Allocate space for aligned image 36 | im_aligned = np.zeros((height,width,3), dtype=np.uint8 ) 37 | 38 | # The blue and green channels will be aligned to the red channel. 39 | # So copy the red channel 40 | im_aligned[:,:,2] = im_color[:,:,2] 41 | 42 | # Define motion model 43 | warp_mode = cv2.MOTION_HOMOGRAPHY 44 | 45 | # Set the warp matrix to identity. 46 | if warp_mode == cv2.MOTION_HOMOGRAPHY : 47 | warp_matrix = np.eye(3, 3, dtype=np.float32) 48 | else : 49 | warp_matrix = np.eye(2, 3, dtype=np.float32) 50 | 51 | # Set the stopping criteria for the algorithm. 52 | criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 50, 1e-10) 53 | 54 | # Warp the blue and green channels to the red channel 55 | for i in range(0,2) : 56 | (cc, warp_matrix) = cv2.findTransformECC (get_gradient(im_color[:,:,2]), get_gradient(im_color[:,:,i]),warp_matrix, warp_mode, criteria) 57 | 58 | if warp_mode == cv2.MOTION_HOMOGRAPHY : 59 | # Use Perspective warp when the transformation is a Homography 60 | im_aligned[:,:,i] = cv2.warpPerspective (im_color[:,:,i], warp_matrix, (width,height), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP) 61 | else : 62 | # Use Affine warp when the transformation is not a Homography 63 | im_aligned[:,:,i] = cv2.warpAffine(im_color[:,:,i], warp_matrix, (width, height), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP); 64 | print(warp_matrix) 65 | 66 | # Show final output 67 | cv2.imshow("Color Image", im_color) 68 | cv2.imshow("Aligned Image", im_aligned) 69 | cv2.waitKey(0) 70 | -------------------------------------------------------------------------------- /ITEM 20-29/ITEM20 OpenCV_ECCAlignment/OpenCV_ECCAlignment_example.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "opencv2/opencv.hpp" 3 | 4 | using namespace cv; 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | // Read the images to be aligned 读取仿射图像 10 | //im1参考图像,im2要处理的图像 11 | Mat im1 = imread("image/image1.jpg"); 12 | Mat im2 = imread("image/image2.jpg"); 13 | 14 | // Convert images to gray scale 转换为灰度图像 15 | Mat im1_gray, im2_gray; 16 | cvtColor(im1, im1_gray, CV_BGR2GRAY); 17 | cvtColor(im2, im2_gray, CV_BGR2GRAY); 18 | 19 | // Define the motion model 定义运动模型 20 | const int warp_mode = MOTION_EUCLIDEAN; 21 | 22 | // Set a 2x3 or 3x3 warp matrix depending on the motion model. 变换矩阵 23 | Mat warp_matrix; 24 | 25 | // Initialize the matrix to identity 26 | if (warp_mode == MOTION_HOMOGRAPHY) 27 | { 28 | warp_matrix = Mat::eye(3, 3, CV_32F); 29 | } 30 | else 31 | { 32 | warp_matrix = Mat::eye(2, 3, CV_32F); 33 | } 34 | 35 | // Specify the number of iterations. 算法迭代次数 36 | int number_of_iterations = 5000; 37 | 38 | // Specify the threshold of the increment 39 | // in the correlation coefficient between two iterations 设定阈值 40 | double termination_eps = 1e-10; 41 | 42 | // Define termination criteria 定义终止条件 43 | TermCriteria criteria(TermCriteria::COUNT + TermCriteria::EPS, number_of_iterations, termination_eps); 44 | 45 | // Run the ECC algorithm. The results are stored in warp_matrix. ECC算法 46 | findTransformECC 47 | ( 48 | im1_gray, 49 | im2_gray, 50 | warp_matrix, 51 | warp_mode, 52 | criteria 53 | ); 54 | 55 | // Storage for warped image. 56 | Mat im2_aligned; 57 | 58 | if (warp_mode != MOTION_HOMOGRAPHY) 59 | { 60 | // Use warpAffine for Translation, Euclidean and Affine 61 | warpAffine(im2, im2_aligned, warp_matrix, im1.size(), INTER_LINEAR + WARP_INVERSE_MAP); 62 | } 63 | else 64 | { 65 | // Use warpPerspective for Homography 66 | warpPerspective(im2, im2_aligned, warp_matrix, im1.size(), INTER_LINEAR + WARP_INVERSE_MAP); 67 | } 68 | 69 | // Show final result 70 | imshow("Image 1", im1); 71 | imshow("Image 2", im2); 72 | imshow("Image 2 Aligned", im2_aligned); 73 | waitKey(0); 74 | 75 | return 0; 76 | } -------------------------------------------------------------------------------- /ITEM 20-29/ITEM20 OpenCV_ECCAlignment/OpenCV_ECCAlignment_example.py: -------------------------------------------------------------------------------- 1 | 2 | import cv2 3 | import numpy as np 4 | 5 | 6 | if __name__ == '__main__': 7 | 8 | # Read the images to be aligned 9 | im1 = cv2.imread("image/image1.jpg"); 10 | im2 = cv2.imread("image/image2.jpg"); 11 | 12 | # Convert images to grayscale 13 | im1_gray = cv2.cvtColor(im1,cv2.COLOR_BGR2GRAY) 14 | im2_gray = cv2.cvtColor(im2,cv2.COLOR_BGR2GRAY) 15 | 16 | # Find size of image1 17 | sz = im1.shape 18 | 19 | # Define the motion model 20 | warp_mode = cv2.MOTION_TRANSLATION 21 | 22 | # Define 2x3 or 3x3 matrices and initialize the matrix to identity 23 | if warp_mode == cv2.MOTION_HOMOGRAPHY : 24 | warp_matrix = np.eye(3, 3, dtype=np.float32) 25 | else : 26 | warp_matrix = np.eye(2, 3, dtype=np.float32) 27 | 28 | # Specify the number of iterations. 29 | number_of_iterations = 5000; 30 | 31 | # Specify the threshold of the increment 32 | # in the correlation coefficient between two iterations 33 | termination_eps = 1e-10; 34 | 35 | # Define termination criteria 36 | criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, number_of_iterations, termination_eps) 37 | 38 | # Run the ECC algorithm. The results are stored in warp_matrix. 39 | (cc, warp_matrix) = cv2.findTransformECC (im1_gray,im2_gray,warp_matrix, warp_mode, criteria) 40 | 41 | 42 | if warp_mode == cv2.MOTION_HOMOGRAPHY : 43 | # Use warpPerspective for Homography 44 | im2_aligned = cv2.warpPerspective (im2, warp_matrix, (sz[1],sz[0]), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP) 45 | else : 46 | # Use warpAffine for Translation, Euclidean and Affine 47 | im2_aligned = cv2.warpAffine(im2, warp_matrix, (sz[1],sz[0]), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP); 48 | 49 | # Show final results 50 | cv2.imshow("Image 1", im1) 51 | cv2.imshow("Image 2", im2) 52 | cv2.imshow("Aligned Image 2", im2_aligned) 53 | cv2.waitKey(0) 54 | -------------------------------------------------------------------------------- /ITEM 20-29/ITEM20 OpenCV_ECCAlignment/image/bridge.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM20 OpenCV_ECCAlignment/image/bridge.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM20 OpenCV_ECCAlignment/image/emir.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM20 OpenCV_ECCAlignment/image/emir.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM20 OpenCV_ECCAlignment/image/girls.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM20 OpenCV_ECCAlignment/image/girls.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM20 OpenCV_ECCAlignment/image/image1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM20 OpenCV_ECCAlignment/image/image1.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM20 OpenCV_ECCAlignment/image/image2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM20 OpenCV_ECCAlignment/image/image2.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM21 OpenCV_EigenFace/dirent.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM21 OpenCV_EigenFace/dirent.h -------------------------------------------------------------------------------- /ITEM 20-29/ITEM21 OpenCV_EigenFace/image/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/luohenyueji/OpenCV-ML-Model/blob/master/OpenCV-Practical-Exercise-Model/images/21OpenCV_EigenFace.zip -------------------------------------------------------------------------------- /ITEM 20-29/ITEM21 OpenCV_EigenFace/pch.cpp: -------------------------------------------------------------------------------- 1 | // pch.cpp: 与预编译标头对应的源文件;编译成功所必需的 2 | 3 | #include "pch.h" 4 | 5 | // 一般情况下,忽略此文件,但如果你使用的是预编译标头,请保留它。 -------------------------------------------------------------------------------- /ITEM 20-29/ITEM22 reconstructFace/createPCAModel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import sys 4 | import cv2 5 | import numpy as np 6 | 7 | # Create data matrix from a list of images 8 | def createDataMatrix(images): 9 | print("Creating data matrix",end=" ... ", flush=True) 10 | ''' 11 | Allocate space for all images in one data matrix. 12 | The size of the data matrix is 13 | 14 | ( w * h * 3, numImages ) 15 | 16 | where, 17 | 18 | w = width of an image in the dataset. 19 | h = height of an image in the dataset. 20 | 3 is for the 3 color channels. 21 | ''' 22 | 23 | numImages = len(images) 24 | sz = images[0].shape 25 | data = np.zeros((numImages, sz[0] * sz[1] * sz[2]), dtype=np.float32) 26 | for i in range(0, numImages): 27 | image = images[i].flatten() 28 | data[i,:] = image 29 | 30 | print("DONE") 31 | return data 32 | 33 | # Read images from the directory 34 | def readImages(path): 35 | print("Reading images from " + path, end=" ... ", flush=True) 36 | # Create array of array of images. 37 | images = [] 38 | # List all files in the directory and read points from text files one by one 39 | for filePath in sorted(os.listdir(path)): 40 | fileExt = os.path.splitext(filePath)[1] 41 | if fileExt in [".jpg", ".jpeg"]: 42 | # Add to array of images 43 | imagePath = os.path.join(path, filePath) 44 | im = cv2.imread(imagePath) 45 | 46 | if im is None : 47 | print("image:{} not read properly".format(imagePath)) 48 | else : 49 | # Convert image to floating point 50 | im = np.float32(im)/255.0 51 | # Add image to list 52 | images.append(im) 53 | # Flip image 54 | imFlip = cv2.flip(im, 1); 55 | # Append flipped image 56 | images.append(imFlip) 57 | 58 | numImages = len(images) / 2 59 | # Exit if no image found 60 | if numImages == 0 : 61 | print("No images found") 62 | sys.exit(0) 63 | 64 | print(str(numImages) + " files read.") 65 | return images 66 | 67 | 68 | 69 | if __name__ == '__main__': 70 | 71 | # Directory containing images 72 | dirName = "image" 73 | 74 | # Read images 75 | images = readImages(dirName) 76 | 77 | # Size of images 78 | sz = images[0].shape 79 | 80 | # Create data matrix for PCA. 81 | data = createDataMatrix(images) 82 | 83 | # Compute the eigenvectors from the stack of images created 84 | print("Calculating PCA ", end=" ... ", flush=True) 85 | mean, eigenVectors = cv2.PCACompute(data, mean=None) 86 | print ("DONE") 87 | 88 | 89 | filename = "pcaParams.yml" 90 | print("Writing size, mean and eigenVectors to " + filename, end=" ... ", flush=True) 91 | file = cv2.FileStorage(filename, cv2.FILE_STORAGE_WRITE) 92 | file.write("mean", mean) 93 | file.write("eigenVectors", eigenVectors) 94 | file.write("size", sz) 95 | file.release() 96 | print("DONE") -------------------------------------------------------------------------------- /ITEM 20-29/ITEM22 reconstructFace/image/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/luohenyueji/OpenCV-ML-Model/blob/master/OpenCV-Practical-Exercise-Model/images/21OpenCV_EigenFace.zip -------------------------------------------------------------------------------- /ITEM 20-29/ITEM22 reconstructFace/reconstructFace.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM22 reconstructFace/reconstructFace.cpp -------------------------------------------------------------------------------- /ITEM 20-29/ITEM22 reconstructFace/test/satya1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM22 reconstructFace/test/satya1.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM22 reconstructFace/test/satya2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM22 reconstructFace/test/satya2.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM23 OpenCV_HDR/OpenCV_HDR.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | 5 | def readImagesAndTimes(): 6 | 7 | times = np.array([ 1/30.0, 0.25, 2.5, 15.0 ], dtype=np.float32) 8 | 9 | filenames = ["./image/img_0.033.jpg", "./image/img_0.25.jpg", "./image/img_2.5.jpg", "./image/img_15.jpg"] 10 | 11 | images = [] 12 | for filename in filenames: 13 | im = cv2.imread(filename) 14 | images.append(im) 15 | 16 | return images, times 17 | 18 | if __name__ == '__main__': 19 | # Read images and exposure times 20 | print("Reading images ... ") 21 | 22 | images, times = readImagesAndTimes() 23 | 24 | 25 | # Align input images 26 | print("Aligning images ... ") 27 | alignMTB = cv2.createAlignMTB() 28 | alignMTB.process(images, images) 29 | 30 | # Obtain Camera Response Function (CRF) 31 | print("Calculating Camera Response Function (CRF) ... ") 32 | calibrateDebevec = cv2.createCalibrateDebevec() 33 | responseDebevec = calibrateDebevec.process(images, times) 34 | 35 | # Merge images into an HDR linear image 36 | print("Merging images into one HDR image ... ") 37 | mergeDebevec = cv2.createMergeDebevec() 38 | hdrDebevec = mergeDebevec.process(images, times, responseDebevec) 39 | # Save HDR image. 40 | cv2.imwrite("hdrDebevec.hdr", hdrDebevec) 41 | print("saved hdrDebevec.hdr ") 42 | 43 | # Tonemap using Drago's method to obtain 24-bit color image 44 | print("Tonemaping using Drago's method ... ") 45 | tonemapDrago = cv2.createTonemapDrago(1.0, 0.7) 46 | ldrDrago = tonemapDrago.process(hdrDebevec) 47 | ldrDrago = 3 * ldrDrago 48 | cv2.imwrite("ldr-Drago.jpg", ldrDrago * 255) 49 | print("saved ldr-Drago.jpg") 50 | 51 | # Tonemap using Durand's method obtain 24-bit color image 52 | print("Tonemaping using Durand's method ... ") 53 | tonemapDurand = cv2.createTonemapDurand(1.5,4,1.0,1,1) 54 | ldrDurand = tonemapDurand.process(hdrDebevec) 55 | ldrDurand = 3 * ldrDurand 56 | cv2.imwrite("ldr-Durand.jpg", ldrDurand * 255) 57 | print("saved ldr-Durand.jpg") 58 | 59 | # Tonemap using Reinhard's method to obtain 24-bit color image 60 | print("Tonemaping using Reinhard's method ... ") 61 | tonemapReinhard = cv2.createTonemapReinhard(1.5, 0,0,0) 62 | ldrReinhard = tonemapReinhard.process(hdrDebevec) 63 | cv2.imwrite("ldr-Reinhard.jpg", ldrReinhard * 255) 64 | print("saved ldr-Reinhard.jpg") 65 | 66 | # Tonemap using Mantiuk's method to obtain 24-bit color image 67 | print("Tonemaping using Mantiuk's method ... ") 68 | tonemapMantiuk = cv2.createTonemapMantiuk(2.2,0.85, 1.2) 69 | ldrMantiuk = tonemapMantiuk.process(hdrDebevec) 70 | ldrMantiuk = 3 * ldrMantiuk 71 | cv2.imwrite("ldr-Mantiuk.jpg", ldrMantiuk * 255) 72 | print("saved ldr-Mantiuk.jpg") 73 | 74 | -------------------------------------------------------------------------------- /ITEM 20-29/ITEM23 OpenCV_HDR/image/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/luohenyueji/OpenCV-ML-Model/blob/master/OpenCV-Practical-Exercise-Model/images/23OpenCV_HDR.zip -------------------------------------------------------------------------------- /ITEM 20-29/ITEM24 OpenCV_ExposureFusion/OpenCV_ExposureFusion.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace cv; 7 | using namespace std; 8 | 9 | // Read Images 10 | void readImages(vector &images) 11 | { 12 | int numImages = 16; 13 | static const char* filenames[] = 14 | { 15 | "image/memorial0061.jpg", 16 | "image/memorial0062.jpg", 17 | "image/memorial0063.jpg", 18 | "image/memorial0064.jpg", 19 | "image/memorial0065.jpg", 20 | "image/memorial0066.jpg", 21 | "image/memorial0067.jpg", 22 | "image/memorial0068.jpg", 23 | "image/memorial0069.jpg", 24 | "image/memorial0070.jpg", 25 | "image/memorial0071.jpg", 26 | "image/memorial0072.jpg", 27 | "image/memorial0073.jpg", 28 | "image/memorial0074.jpg", 29 | "image/memorial0075.jpg", 30 | "image/memorial0076.jpg" 31 | }; 32 | //读图 33 | for (int i = 0; i < numImages; i++) 34 | { 35 | Mat im = imread(filenames[i]); 36 | images.push_back(im); 37 | } 38 | } 39 | 40 | int main() 41 | { 42 | // Read images 读取图像 43 | cout << "Reading images ... " << endl; 44 | vector images; 45 | 46 | //是否图像映射 47 | bool needsAlignment = true; 48 | 49 | // Read example images 读取例子图像 50 | readImages(images); 51 | //needsAlignment = false; 52 | 53 | // Align input images 54 | if (needsAlignment) 55 | { 56 | cout << "Aligning images ... " << endl; 57 | Ptr alignMTB = createAlignMTB(); 58 | alignMTB->process(images, images); 59 | } 60 | else 61 | { 62 | cout << "Skipping alignment ... " << endl; 63 | } 64 | 65 | // Merge using Exposure Fusion 图像融合 66 | cout << "Merging using Exposure Fusion ... " << endl; 67 | Mat exposureFusion; 68 | Ptr mergeMertens = createMergeMertens(); 69 | mergeMertens->process(images, exposureFusion); 70 | 71 | // Save output image 图像保存 72 | cout << "Saving output ... exposure-fusion.jpg" << endl; 73 | imwrite("exposure-fusion.jpg", exposureFusion * 255); 74 | 75 | return 0; 76 | } -------------------------------------------------------------------------------- /ITEM 20-29/ITEM24 OpenCV_ExposureFusion/OpenCV_ExposureFusion.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import sys 4 | 5 | 6 | def readImagesAndTimes(): 7 | 8 | filenames = [ 9 | "image/memorial0061.jpg", 10 | "image/memorial0062.jpg", 11 | "image/memorial0063.jpg", 12 | "image/memorial0064.jpg", 13 | "image/memorial0065.jpg", 14 | "image/memorial0066.jpg", 15 | "image/memorial0067.jpg", 16 | "image/memorial0068.jpg", 17 | "image/memorial0069.jpg", 18 | "image/memorial0070.jpg", 19 | "image/memorial0071.jpg", 20 | "image/memorial0072.jpg", 21 | "image/memorial0073.jpg", 22 | "image/memorial0074.jpg", 23 | "image/memorial0075.jpg", 24 | "image/memorial0076.jpg" 25 | ] 26 | 27 | images = [] 28 | for filename in filenames: 29 | im = cv2.imread(filename) 30 | images.append(im) 31 | 32 | return images 33 | 34 | if __name__ == '__main__': 35 | 36 | # Read images 37 | print("Reading images ... ") 38 | 39 | if len(sys.argv) > 1: 40 | # Read images from the command line 41 | images = [] 42 | for filename in sys.argv[1:]: 43 | im = cv2.imread(filename) 44 | images.append(im) 45 | needsAlignment = False 46 | else : 47 | # Read example images 48 | images = readImagesAndTimes() 49 | needsAlignment = False 50 | 51 | # Align input images 52 | if needsAlignment: 53 | print("Aligning images ... ") 54 | alignMTB = cv2.createAlignMTB() 55 | alignMTB.process(images, images) 56 | else : 57 | print("Skipping alignment ... ") 58 | 59 | # Merge using Exposure Fusion 60 | print("Merging using Exposure Fusion ... "); 61 | mergeMertens = cv2.createMergeMertens() 62 | exposureFusion = mergeMertens.process(images) 63 | 64 | # Save output image 65 | print("Saving output ... exposure-fusion.jpg") 66 | cv2.imwrite("exposure-fusion.jpg", exposureFusion * 255) 67 | 68 | 69 | -------------------------------------------------------------------------------- /ITEM 20-29/ITEM24 OpenCV_ExposureFusion/image/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/luohenyueji/OpenCV-ML-Model/blob/master/OpenCV-Practical-Exercise-Model/images/24OpenCV_ExposureFusion.zip -------------------------------------------------------------------------------- /ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/OpenCV_SeamlessCloning.cpp: -------------------------------------------------------------------------------- 1 | // OpenCV_SeamlessCloning.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 2 | // 3 | 4 | #include "pch.h" 5 | #include 6 | #include 7 | 8 | using namespace cv; 9 | using namespace std; 10 | 11 | int main() 12 | { 13 | // Read images : src image will be cloned into dst 14 | //目标图像 15 | Mat src = imread("image/airplane.jpg"); 16 | //背景图像 17 | Mat dst = imread("image/sky.jpg"); 18 | 19 | // Create a rough mask around the airplane. 创建掩模 20 | Mat src_mask = Mat::zeros(src.rows, src.cols, src.depth()); 21 | 22 | // Define the mask as a closed polygon 定义轮廓类似目标物体的多边形 23 | Point poly[1][7]; 24 | poly[0][0] = Point(4, 80); 25 | poly[0][1] = Point(30, 54); 26 | poly[0][2] = Point(151, 63); 27 | poly[0][3] = Point(254, 37); 28 | poly[0][4] = Point(298, 90); 29 | poly[0][5] = Point(272, 134); 30 | poly[0][6] = Point(43, 122); 31 | 32 | const Point* polygons[1] = { poly[0] }; 33 | int num_points[] = { 7 }; 34 | 35 | // Create mask by filling the polygon 填充多边形 36 | fillPoly(src_mask, polygons, num_points, 1, Scalar(255, 255, 255)); 37 | 38 | // The location of the center of the src in the dst 目标图像在背景图像中心点左边 39 | Point center(800, 100); 40 | 41 | // Seamlessly clone src into dst and put the results in output 42 | Mat output; 43 | seamlessClone(src, dst, src_mask, center, output, NORMAL_CLONE); 44 | 45 | // Write result 46 | imwrite("opencv-seamless-cloning-example.jpg", output); 47 | imshow("result", output); 48 | waitKey(0); 49 | return 0; 50 | } -------------------------------------------------------------------------------- /ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/OpenCV_SeamlessCloning.py: -------------------------------------------------------------------------------- 1 | 2 | import cv2 3 | import numpy as np 4 | 5 | # Read images 6 | src = cv2.imread("image/airplane.jpg") 7 | dst = cv2.imread("image/sky.jpg") 8 | 9 | 10 | # Create a rough mask around the airplane. 11 | src_mask = np.zeros(src.shape, src.dtype) 12 | poly = np.array([ [4,80], [30,54], [151,63], [254,37], [298,90], [272,134], [43,122] ], np.int32) 13 | cv2.fillPoly(src_mask, [poly], (255, 255, 255)) 14 | 15 | # This is where the CENTER of the airplane will be placed 16 | center = (800,100) 17 | 18 | # Clone seamlessly. 19 | output = cv2.seamlessClone(src, dst, src_mask, center, cv2.NORMAL_CLONE) 20 | 21 | # Write result 22 | cv2.imwrite("opencv-seamless-cloning-example.jpg", output); 23 | 24 | 25 | -------------------------------------------------------------------------------- /ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/image/airplane.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/image/airplane.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/image/iloveyouticket.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/image/iloveyouticket.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/image/sky.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/image/sky.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/image/wood-texture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/image/wood-texture.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/normal_versus_mixed_clone.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/normal_versus_mixed_clone.cpp -------------------------------------------------------------------------------- /ITEM 20-29/ITEM25 OpenCV_SeamlessCloning/normal_versus_mixed_clone.py: -------------------------------------------------------------------------------- 1 | 2 | import cv2 3 | import numpy as np 4 | 5 | # Read images : src image will be cloned into dst 6 | im = cv2.imread("image/wood-texture.jpg") 7 | obj= cv2.imread("image/iloveyouticket.jpg") 8 | 9 | # Create an all white mask 10 | mask = 255 * np.ones(obj.shape, obj.dtype) 11 | 12 | # The location of the center of the src in the dst 13 | width, height, channels = im.shape 14 | center = (int(height/2), int(width/2)) 15 | 16 | # Seamlessly clone src into dst and put the results in output 17 | normal_clone = cv2.seamlessClone(obj, im, mask, center, cv2.NORMAL_CLONE) 18 | mixed_clone = cv2.seamlessClone(obj, im, mask, center, cv2.MIXED_CLONE) 19 | monochrome_clone = cv2.seamlessClone(obj, im, mask, center, cv2.MONOCHROME_TRANSFER) 20 | # Write results 21 | cv2.imwrite("opencv-normal-clone-example.jpg", normal_clone) 22 | cv2.imwrite("opencv-mixed-clone-example.jpg", mixed_clone) 23 | cv2.imwrite("opencv-monochrome-clone-example.jpg", monochrome_clone) -------------------------------------------------------------------------------- /ITEM 20-29/ITEM26 OpenCV_SelectiveSearch/OpenCV_SelectiveSearch.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM26 OpenCV_SelectiveSearch/OpenCV_SelectiveSearch.cpp -------------------------------------------------------------------------------- /ITEM 20-29/ITEM26 OpenCV_SelectiveSearch/OpenCV_SelectiveSearch.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | import cv2 4 | 5 | if __name__ == '__main__': 6 | 7 | # speed-up using multithreads 8 | cv2.setUseOptimized(True) 9 | cv2.setNumThreads(4); 10 | 11 | # read image 12 | im = cv2.imread('image/dogs.jpg') 13 | # resize image 14 | newHeight = 200 15 | newWidth = int(im.shape[1]*200/im.shape[0]) 16 | im = cv2.resize(im, (newWidth, newHeight)) 17 | 18 | # create Selective Search Segmentation Object using default parameters 19 | ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() 20 | 21 | # set input image on which we will run segmentation 22 | ss.setBaseImage(im) 23 | 24 | 25 | #ss.switchToSelectiveSearchFast() 26 | 27 | ss.switchToSelectiveSearchQuality() 28 | 29 | 30 | # run selective search segmentation on input image 31 | rects = ss.process() 32 | print('Total Number of Region Proposals: {}'.format(len(rects))) 33 | 34 | # number of region proposals to show 35 | numShowRects = 100 36 | # increment to increase/decrease total number 37 | # of reason proposals to be shown 38 | increment = 50 39 | 40 | while True: 41 | # create a copy of original image 42 | imOut = im.copy() 43 | 44 | # itereate over all the region proposals 45 | for i, rect in enumerate(rects): 46 | # draw rectangle for region proposal till numShowRects 47 | if (i < numShowRects): 48 | x, y, w, h = rect 49 | cv2.rectangle(imOut, (x, y), (x+w, y+h), (0, 255, 0), 1, cv2.LINE_AA) 50 | else: 51 | break 52 | 53 | # show output 54 | cv2.imshow("Output", imOut); 55 | 56 | # record key press 57 | k = cv2.waitKey(0) & 0xFF 58 | 59 | # m is pressed 60 | if k == 109: 61 | # increase total number of rectangles to show by increment 62 | numShowRects += increment 63 | # l is pressed 64 | elif k == 108 and numShowRects > increment: 65 | # decrease total number of rectangles to show by increment 66 | numShowRects -= increment 67 | # q is pressed 68 | elif k == 113: 69 | break 70 | # close image show window 71 | cv2.destroyAllWindows() 72 | -------------------------------------------------------------------------------- /ITEM 20-29/ITEM26 OpenCV_SelectiveSearch/image/breakfast.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM26 OpenCV_SelectiveSearch/image/breakfast.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM26 OpenCV_SelectiveSearch/image/dogs.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM26 OpenCV_SelectiveSearch/image/dogs.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM27 OpenCV_forEach/image/butterfly.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM27 OpenCV_forEach/image/butterfly.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM28 OpenCV_cvui/canny.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM28 OpenCV_cvui/canny.cpp -------------------------------------------------------------------------------- /ITEM 20-29/ITEM28 OpenCV_cvui/hello-world.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM28 OpenCV_cvui/hello-world.cpp -------------------------------------------------------------------------------- /ITEM 20-29/ITEM28 OpenCV_cvui/image/lena.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM28 OpenCV_cvui/image/lena.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM29 OpenCV_RedEyeRemover/OpenCV_RedEyeRemover.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM29 OpenCV_RedEyeRemover/OpenCV_RedEyeRemover.cpp -------------------------------------------------------------------------------- /ITEM 20-29/ITEM29 OpenCV_RedEyeRemover/OpenCV_RedEyeRemover.py: -------------------------------------------------------------------------------- 1 | 2 | import cv2 3 | import numpy as np 4 | 5 | 6 | def fillHoles(mask): 7 | 8 | maskFloodfill = mask.copy() 9 | h, w = maskFloodfill.shape[:2] 10 | maskTemp = np.zeros((h+2, w+2), np.uint8) 11 | cv2.floodFill(maskFloodfill, maskTemp, (0, 0), 255) 12 | mask2 = cv2.bitwise_not(maskFloodfill) 13 | return mask2 | mask 14 | 15 | if __name__ == '__main__' : 16 | 17 | # Read image 18 | img = cv2.imread("./image/red_eyes.jpg", cv2.IMREAD_COLOR) 19 | 20 | # Output image 21 | imgOut = img.copy() 22 | 23 | # Load HAAR cascade 24 | eyesCascade = cv2.CascadeClassifier("./model/haarcascade_eye.xml") 25 | 26 | # Detect eyes 27 | eyes = eyesCascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(100, 100)) 28 | 29 | # For every detected eye 30 | for (x, y, w, h) in eyes: 31 | 32 | # Extract eye from the image 33 | eye = img[y:y+h, x:x+w] 34 | 35 | # Split eye image into 3 channels 36 | b = eye[:, :, 0] 37 | g = eye[:, :, 1] 38 | r = eye[:, :, 2] 39 | 40 | # Add the green and blue channels. 41 | bg = cv2.add(b, g) 42 | 43 | # Simple red eye detector. 44 | mask = (r > 150) & (r > bg) 45 | 46 | # Convert the mask to uint8 format. 47 | mask = mask.astype(np.uint8)*255 48 | 49 | # Clean mask -- 1) File holes 2) Dilate (expand) mask. 50 | mask = fillHoles(mask) 51 | mask = cv2.dilate(mask, None, anchor=(-1, -1), iterations=3, borderType=1, borderValue=1) 52 | 53 | # Calculate the mean channel by averaging 54 | # the green and blue channels 55 | mean = bg / 2 56 | mask = mask.astype(np.bool)[:, :, np.newaxis] 57 | mean = mean[:, :, np.newaxis] 58 | 59 | # Copy the eye from the original image. 60 | eyeOut = eye.copy() 61 | 62 | # Copy the mean image to the output image. 63 | #np.copyto(eyeOut, mean, where=mask) 64 | eyeOut = np.where(mask, mean, eyeOut) 65 | 66 | # Copy the fixed eye to the output image. 67 | imgOut[y:y+h, x:x+w, :] = eyeOut 68 | 69 | # Display Result 70 | cv2.imshow('Red Eyes', img) 71 | cv2.imshow('Red Eyes Removed', imgOut) 72 | cv2.waitKey(0) 73 | -------------------------------------------------------------------------------- /ITEM 20-29/ITEM29 OpenCV_RedEyeRemover/image/red_eyes.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM29 OpenCV_RedEyeRemover/image/red_eyes.jpg -------------------------------------------------------------------------------- /ITEM 20-29/ITEM29 OpenCV_RedEyeRemover/image/red_eyes2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 20-29/ITEM29 OpenCV_RedEyeRemover/image/red_eyes2.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM30 OpenCV_FillHoles/OpenCV_FillHoles.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include 3 | 4 | using namespace cv; 5 | 6 | int main() 7 | { 8 | // Read image 读取图像 9 | Mat im_in = imread("./image/nickel.jpg", IMREAD_GRAYSCALE); 10 | 11 | 12 | // Threshold. 13 | // Set values equal to or above 220 to 0. 14 | // Set values below 220 to 255. 15 | //阈值分割 16 | Mat im_th; 17 | threshold(im_in, im_th, 220, 255, THRESH_BINARY_INV); 18 | 19 | // Floodfill from point (0, 0) 以点(0,0)为种子点,进行漫水填充 20 | Mat im_floodfill = im_th.clone(); 21 | floodFill(im_floodfill, cv::Point(0,0), Scalar(255)); 22 | 23 | // Invert floodfilled image 反转图像 24 | Mat im_floodfill_inv; 25 | bitwise_not(im_floodfill, im_floodfill_inv); 26 | 27 | // Combine the two images to get the foreground. 获得前景 28 | Mat im_out = (im_th | im_floodfill_inv); 29 | 30 | // Display images 图像展示 31 | imshow("Thresholded Image", im_th); 32 | imshow("Floodfilled Image", im_floodfill); 33 | imshow("Inverted Floodfilled Image", im_floodfill_inv); 34 | imshow("Foreground", im_out); 35 | waitKey(0); 36 | return 0; 37 | } -------------------------------------------------------------------------------- /ITEM 30-39/ITEM30 OpenCV_FillHoles/OpenCV_FillHoles.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2; 4 | import numpy as np; 5 | 6 | # Read image 7 | im_in = cv2.imread("./image/nickel.jpg", cv2.IMREAD_GRAYSCALE); 8 | 9 | # Threshold. 10 | # Set values equal to or above 220 to 0. 11 | # Set values below 220 to 255. 12 | 13 | th, im_th = cv2.threshold(im_in, 220, 255, cv2.THRESH_BINARY_INV); 14 | 15 | # Copy the thresholded image. 16 | im_floodfill = im_th.copy() 17 | 18 | # Mask used to flood filling. 19 | # Notice the size needs to be 2 pixels than the image. 20 | h, w = im_th.shape[:2] 21 | mask = np.zeros((h+2, w+2), np.uint8) 22 | 23 | # Floodfill from point (0, 0) 24 | cv2.floodFill(im_floodfill, mask, (0,0), 255); 25 | 26 | # Invert floodfilled image 27 | im_floodfill_inv = cv2.bitwise_not(im_floodfill) 28 | 29 | # Combine the two images to get the foreground. 30 | im_out = im_th | im_floodfill_inv 31 | 32 | # Display images. 33 | cv2.imshow("Thresholded Image", im_th) 34 | cv2.imshow("Floodfilled Image", im_floodfill) 35 | cv2.imshow("Inverted Floodfilled Image", im_floodfill_inv) 36 | cv2.imshow("Foreground", im_out) 37 | cv2.waitKey(0) -------------------------------------------------------------------------------- /ITEM 30-39/ITEM30 OpenCV_FillHoles/image/nickel.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM30 OpenCV_FillHoles/image/nickel.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM31 OpenCV_WarpTriangle/OpenCV_WarpTriangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright (c) 2016 Satya Mallick 4 | # All rights reserved. No warranty, explicit or implicit, provided. 5 | 6 | import cv2 7 | import numpy as np 8 | 9 | 10 | # Warps and alpha blends triangular regions from img1 and img2 to img 11 | def warpTriangle(img1, img2, tri1, tri2) : 12 | 13 | # Find bounding rectangle for each triangle 14 | r1 = cv2.boundingRect(tri1) 15 | r2 = cv2.boundingRect(tri2) 16 | 17 | # Offset points by left top corner of the respective rectangles 18 | tri1Cropped = [] 19 | tri2Cropped = [] 20 | 21 | for i in range(0, 3): 22 | tri1Cropped.append(((tri1[0][i][0] - r1[0]),(tri1[0][i][1] - r1[1]))) 23 | tri2Cropped.append(((tri2[0][i][0] - r2[0]),(tri2[0][i][1] - r2[1]))) 24 | 25 | # Crop input image 26 | img1Cropped = img1[r1[1]:r1[1] + r1[3], r1[0]:r1[0] + r1[2]] 27 | 28 | # Given a pair of triangles, find the affine transform. 29 | warpMat = cv2.getAffineTransform( np.float32(tri1Cropped), np.float32(tri2Cropped) ) 30 | 31 | # Apply the Affine Transform just found to the src image 32 | img2Cropped = cv2.warpAffine( img1Cropped, warpMat, (r2[2], r2[3]), None, flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101 ) 33 | 34 | # Get mask by filling triangle 35 | mask = np.zeros((r2[3], r2[2], 3), dtype = np.float32) 36 | cv2.fillConvexPoly(mask, np.int32(tri2Cropped), (1.0, 1.0, 1.0), 16, 0); 37 | 38 | img2Cropped = img2Cropped * mask 39 | 40 | # Copy triangular region of the rectangular patch to the output image 41 | img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] = img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] * ( (1.0, 1.0, 1.0) - mask ) 42 | 43 | img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] = img2[r2[1]:r2[1]+r2[3], r2[0]:r2[0]+r2[2]] + img2Cropped 44 | 45 | 46 | if __name__ == '__main__' : 47 | 48 | # Read input image 49 | imgIn = cv2.imread("./image/robot.jpg") 50 | 51 | # Output image is set to white 52 | imgOut = 255 * np.ones(imgIn.shape, dtype = imgIn.dtype) 53 | 54 | # Input triangle 55 | triIn = np.float32([[[360,200], [60,250], [450,400]]]) 56 | 57 | # Output triangle 58 | triOut = np.float32([[[400,200], [160,270], [400,400]]]) 59 | 60 | # Warp all pixels inside input triangle to output triangle 61 | warpTriangle(imgIn, imgOut, triIn, triOut) 62 | 63 | # Draw triangle using this color 64 | color = (255, 150, 0) 65 | 66 | # Draw triangles in input and output images. 67 | cv2.polylines(imgIn, triIn.astype(int), True, color, 2, 16) 68 | cv2.polylines(imgOut, triOut.astype(int), True, color, 2, 16) 69 | 70 | cv2.imshow("Input", imgIn) 71 | cv2.imshow("Output", imgOut) 72 | 73 | 74 | cv2.waitKey(0) 75 | 76 | 77 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM31 OpenCV_WarpTriangle/image/robot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM31 OpenCV_WarpTriangle/image/robot.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM32 OpenCV_NonPhotorealisticRendering/OpenCV_NonPhotorealisticRendering.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM32 OpenCV_NonPhotorealisticRendering/OpenCV_NonPhotorealisticRendering.cpp -------------------------------------------------------------------------------- /ITEM 30-39/ITEM32 OpenCV_NonPhotorealisticRendering/OpenCV_NonPhotorealisticRendering.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import cv2 4 | 5 | # Read image 6 | im = cv2.imread("./image/cow.jpg"); 7 | 8 | # Edge preserving filter with two different flags. 9 | imout = cv2.edgePreservingFilter(im, flags=cv2.RECURS_FILTER); 10 | cv2.imwrite("edge-preserving-recursive-filter.jpg", imout); 11 | 12 | imout = cv2.edgePreservingFilter(im, flags=cv2.NORMCONV_FILTER); 13 | cv2.imwrite("edge-preserving-normalized-convolution-filter.jpg", imout); 14 | 15 | # Detail enhance filter 16 | imout = cv2.detailEnhance(im); 17 | cv2.imwrite("detail-enhance.jpg", imout); 18 | 19 | # Pencil sketch filter 20 | imout_gray, imout = cv2.pencilSketch(im, sigma_s=60, sigma_r=0.07, shade_factor=0.05); 21 | cv2.imwrite("pencil-sketch.jpg", imout_gray); 22 | cv2.imwrite("pencil-sketch-color.jpg", imout); 23 | 24 | # Stylization filter 25 | cv2.stylization(im,imout); 26 | cv2.imwrite("stylization.jpg", imout); 27 | 28 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM32 OpenCV_NonPhotorealisticRendering/image/cow.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM32 OpenCV_NonPhotorealisticRendering/image/cow.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM33 OpenCV_HoughTransform/hough_circles.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM33 OpenCV_HoughTransform/hough_circles.cpp -------------------------------------------------------------------------------- /ITEM 30-39/ITEM33 OpenCV_HoughTransform/hough_circles.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import sys 4 | 5 | def onTrackbarChange(max_slider): 6 | cimg = np.copy(img) 7 | 8 | p1 = max_slider 9 | p2 = max_slider * 0.4 10 | 11 | # Detect circles using HoughCircles transform 12 | circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, cimg.shape[0]/64, param1=p1, param2=p2, minRadius=25, maxRadius=50) 13 | 14 | # If at least 1 circle is detected 15 | if circles is not None: 16 | cir_len = circles.shape[1] # store length of circles found 17 | circles = np.uint16(np.around(circles)) 18 | for i in circles[0, :]: 19 | # Draw the outer circle 20 | cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2) 21 | # Draw the center of the circle 22 | cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3) 23 | else: 24 | cir_len = 0 # no circles detected 25 | 26 | # Display output image 27 | cv2.imshow('Image', cimg) 28 | 29 | # Edge image for debugging 30 | edges = cv2.Canny(gray, p1, p2) 31 | cv2.imshow('Edges', edges) 32 | 33 | 34 | 35 | 36 | if __name__ == "__main__": 37 | # Read image 38 | img = cv2.imread("./image/brown-eyes.jpg") 39 | 40 | # Convert to gray-scale 41 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 42 | 43 | # Create display windows 44 | cv2.namedWindow("Edges") 45 | cv2.namedWindow("Image") 46 | 47 | 48 | # Trackbar will be used for changing threshold for edge 49 | initThresh = 105 50 | maxThresh = 200 51 | 52 | # Create trackbar 53 | cv2.createTrackbar("Threshold", "Image", initThresh, maxThresh, onTrackbarChange) 54 | onTrackbarChange(initThresh) 55 | 56 | while True: 57 | key = cv2.waitKey(1) 58 | if key == 27: 59 | break 60 | 61 | cv2.destroyAllWindows() 62 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM33 OpenCV_HoughTransform/hough_lines.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM33 OpenCV_HoughTransform/hough_lines.cpp -------------------------------------------------------------------------------- /ITEM 30-39/ITEM33 OpenCV_HoughTransform/hough_lines.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | def onTrackbarChange(max_slider): 5 | global img 6 | global dst 7 | global gray 8 | 9 | dst = np.copy(img) 10 | 11 | th1 = max_slider 12 | th2 = th1 * 0.4 13 | edges = cv2.Canny(img, th1, th2) 14 | 15 | # Apply probabilistic hough line transform 16 | lines = cv2.HoughLinesP(edges, 2, np.pi/180.0, 50, minLineLength=10, maxLineGap=100) 17 | 18 | # Draw lines on the detected points 19 | for line in lines: 20 | x1, y1, x2, y2 = line[0] 21 | cv2.line(dst, (x1, y1), (x2, y2), (0,0,255), 1) 22 | 23 | cv2.imshow("Result Image", dst) 24 | cv2.imshow("Edges",edges) 25 | 26 | if __name__ == "__main__": 27 | 28 | # Read image 29 | img = cv2.imread('./image/lanes.jpg') 30 | 31 | # Create a copy for later usage 32 | dst = np.copy(img) 33 | 34 | # Convert image to gray 35 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 36 | 37 | # Create display windows 38 | cv2.namedWindow("Edges") 39 | cv2.namedWindow("Result Image") 40 | 41 | 42 | # Initialize threshold value 43 | initThresh = 500 44 | 45 | # Maximum threshold value 46 | maxThresh = 1000 47 | 48 | cv2.createTrackbar("threshold", "Result Image", initThresh, maxThresh, onTrackbarChange) 49 | onTrackbarChange(initThresh) 50 | 51 | while True: 52 | key = cv2.waitKey(1) 53 | if key == 27: 54 | break 55 | 56 | cv2.destroyAllWindows() 57 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM33 OpenCV_HoughTransform/image/brown-eyes.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM33 OpenCV_HoughTransform/image/brown-eyes.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM33 OpenCV_HoughTransform/image/lanes.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM33 OpenCV_HoughTransform/image/lanes.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM34 OpenCV_Inpainting/OpenCV_Inpainting.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include 3 | #include 4 | 5 | #include 6 | 7 | using namespace cv; 8 | using namespace std; 9 | 10 | // Declare Mat objects for original image and mask for inpainting 11 | Mat img, inpaintMask; 12 | // Mat object for result output 13 | Mat res; 14 | Point prevPt(-1, -1); 15 | 16 | // onMouse function for Mouse Handling 17 | // Used to draw regions required to inpaint 18 | // 调用鼠标事件 19 | static void onMouse(int event, int x, int y, int flags, void*) 20 | { 21 | if (event == EVENT_LBUTTONUP || !(flags & EVENT_FLAG_LBUTTON)) 22 | prevPt = Point(-1, -1); 23 | else if (event == EVENT_LBUTTONDOWN) 24 | prevPt = Point(x, y); 25 | else if (event == EVENT_MOUSEMOVE && (flags & EVENT_FLAG_LBUTTON)) 26 | { 27 | Point pt(x, y); 28 | if (prevPt.x < 0) 29 | prevPt = pt; 30 | line(inpaintMask, prevPt, pt, Scalar::all(255), 5, 8, 0); 31 | line(img, prevPt, pt, Scalar::all(255), 5, 8, 0); 32 | prevPt = pt; 33 | imshow("image", img); 34 | imshow("image: mask", inpaintMask); 35 | } 36 | } 37 | 38 | int main() 39 | { 40 | string filename = "./image/flower-garden.jpg"; 41 | // Read image in color mode 读图 42 | img = imread(filename); 43 | Mat img_mask; 44 | // Return error if image not read properly 45 | if (img.empty()) 46 | { 47 | cout << "Failed to load image: " << filename << endl; 48 | return 0; 49 | } 50 | 51 | namedWindow("image"); 52 | 53 | // Create a copy for the original image 复制原图像 54 | img_mask = img.clone(); 55 | // Initialize mask (black image) 56 | inpaintMask = Mat::zeros(img_mask.size(), CV_8U); 57 | 58 | // Show the original image 59 | imshow("image", img); 60 | //调用鼠标在图像上画圈 61 | setMouseCallback("image", onMouse, NULL); 62 | 63 | for (;;) 64 | { 65 | char c = (char)waitKey(); 66 | //按t选择INPAINT_TELEA处理 67 | if (c == 't') 68 | { 69 | // Use Algorithm proposed by Alexendra Telea 70 | inpaint(img, inpaintMask, res, 3, INPAINT_TELEA); 71 | imshow("Inpaint Output using FMM", res); 72 | } 73 | //按n选择INPAINT_NS处理 74 | if (c == 'n') 75 | { 76 | // Use Algorithm proposed by Bertalmio et. al. 77 | inpaint(img, inpaintMask, res, 3, INPAINT_NS); 78 | imshow("Inpaint Output using NS Technique", res); 79 | } 80 | //按r查看原图 81 | if (c == 'r') 82 | { 83 | inpaintMask = Scalar::all(0); 84 | img_mask.copyTo(img); 85 | imshow("image", inpaintMask); 86 | } 87 | //按ESC退出 88 | if (c == 27) 89 | { 90 | break; 91 | } 92 | } 93 | return 0; 94 | } -------------------------------------------------------------------------------- /ITEM 30-39/ITEM34 OpenCV_Inpainting/image/Lincoln.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM34 OpenCV_Inpainting/image/Lincoln.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM34 OpenCV_Inpainting/image/flower-garden.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM34 OpenCV_Inpainting/image/flower-garden.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM34 OpenCV_Inpainting/image/sample.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM34 OpenCV_Inpainting/image/sample.jpeg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM35 OpenCV_Tesseract/OpenCV_Tesseract.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | using namespace cv; 8 | 9 | int main() 10 | { 11 | string outText; 12 | string imPath = "image/receipt.png"; 13 | 14 | // Create Tesseract object 15 | tesseract::TessBaseAPI *ocr = new tesseract::TessBaseAPI(); 16 | 17 | /* 18 | Initialize OCR engine to use English (eng) and The LSTM 19 | OCR engine. 20 | 21 | 22 | There are four OCR Engine Mode (oem) available 23 | 24 | OEM_TESSERACT_ONLY Legacy engine only. 25 | OEM_LSTM_ONLY Neural nets LSTM engine only. 26 | OEM_TESSERACT_LSTM_COMBINED Legacy + LSTM engines. 27 | OEM_DEFAULT Default, based on what is available. 28 | */ 29 | // 初始化 30 | ocr->Init(NULL, "eng", tesseract::OEM_LSTM_ONLY); 31 | 32 | 33 | // Set Page segmentation mode to PSM_AUTO (3) 34 | // Other important psm modes will be discussed in a future post. 35 | // 设置分割模式 36 | ocr->SetPageSegMode(tesseract::PSM_AUTO); 37 | 38 | 39 | // Open input image using OpenCV 40 | Mat im = cv::imread(imPath, IMREAD_COLOR); 41 | 42 | // Set image data 43 | ocr->SetImage(im.data, im.cols, im.rows, 3, im.step); 44 | 45 | // Run Tesseract OCR on image 46 | outText = string(ocr->GetUTF8Text()); 47 | 48 | // print recognized text 49 | cout << outText << endl; 50 | 51 | // Destroy used object and release memory 52 | ocr->End(); 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM35 OpenCV_Tesseract/OpenCV_Tesseract.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import pytesseract 3 | 4 | 5 | # 图像路径 6 | imPath = 'image/computer-vision.jpg' 7 | 8 | 9 | # 命令 10 | config = ('-l eng --oem 1 --psm 3') 11 | 12 | # Read image from disk 获得彩色图像 13 | im = cv2.imread(imPath, cv2.IMREAD_COLOR) 14 | 15 | # Run tesseract OCR on image 16 | text = pytesseract.image_to_string(im, config=config) 17 | 18 | # Print recognized text 19 | print(text) 20 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM35 OpenCV_Tesseract/image/computer-vision.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM35 OpenCV_Tesseract/image/computer-vision.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM35 OpenCV_Tesseract/image/receipt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM35 OpenCV_Tesseract/image/receipt.png -------------------------------------------------------------------------------- /ITEM 30-39/ITEM35 OpenCV_Tesseract/image/road-sign-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM35 OpenCV_Tesseract/image/road-sign-1.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM35 OpenCV_Tesseract/image/road-sign-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM35 OpenCV_Tesseract/image/road-sign-2.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM35 OpenCV_Tesseract/image/road-sign-3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM35 OpenCV_Tesseract/image/road-sign-3.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM36 OpenCV_BackgroundEstimation/OpenCV_BackgroundEstimation.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | 4 | # Open Video 5 | cap = cv2.VideoCapture('video/video.mp4') 6 | 7 | # Randomly select 25 frames 8 | frameIds = cap.get(cv2.CAP_PROP_FRAME_COUNT) * np.random.uniform(size=25) 9 | 10 | # Store selected frames in an array 11 | frames = [] 12 | for fid in frameIds: 13 | cap.set(cv2.CAP_PROP_POS_FRAMES, fid) 14 | ret, frame = cap.read() 15 | frames.append(frame) 16 | 17 | # Calculate the median along the time axis 18 | medianFrame = np.median(frames, axis=0).astype(dtype=np.uint8) 19 | 20 | # Display median frame 21 | cv2.imshow('frame', medianFrame) 22 | cv2.waitKey(0) 23 | 24 | # Reset frame number to 0 25 | cap.set(cv2.CAP_PROP_POS_FRAMES, 0) 26 | 27 | # Convert background to grayscale 28 | grayMedianFrame = cv2.cvtColor(medianFrame, cv2.COLOR_BGR2GRAY) 29 | 30 | # Loop over all frames 31 | ret = True 32 | while(ret): 33 | 34 | # Read frame 35 | ret, frame = cap.read() 36 | if frame is None: 37 | break 38 | # Convert current frame to grayscale 39 | frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 40 | # Calculate absolute difference of current frame and 41 | # the median frame 42 | dframe = cv2.absdiff(frame, grayMedianFrame) 43 | # Treshold to binarize 44 | th, dframe = cv2.threshold(dframe, 30, 255, cv2.THRESH_BINARY) 45 | # Display image 46 | cv2.imshow('frame', dframe) 47 | cv2.waitKey(20) 48 | 49 | # Release video object 50 | cap.release() 51 | 52 | # Destroy all windows 53 | cv2.destroyAllWindows() 54 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM36 OpenCV_BackgroundEstimation/video/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/luohenyueji/OpenCV-ML-Model/blob/master/OpenCV-Practical-Exercise-Model/videos/36OpenCV_BackgroundEstimation.7z -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/allrange: -------------------------------------------------------------------------------- 1 | x 2 | -1 1 3 | 1 0.338 10 4 | 2 0.017204 0.806612 5 | 3 0.236 1.642 6 | 4 -0.123884 0.20293 7 | 5 0.000155 0.712298 8 | 6 0.001122 0.470257 9 | 7 0.244 1.641 10 | 8 -0.123586 0.179083 11 | 9 0.000152 0.710456 12 | 10 0.000975 0.470984 13 | 11 0.249 1.555 14 | 12 -0.135687 0.100858 15 | 13 0.000174 0.684173 16 | 14 0.000913 0.534174 17 | 15 0.258 1.561 18 | 16 -0.143408 0.100486 19 | 17 0.000179 0.685696 20 | 18 0.000888 0.536508 21 | 19 0.471 3.264 22 | 20 0.012809 0.703171 23 | 21 0.218 1.046 24 | 22 -0.094876 0.187459 25 | 23 1.5e-005 0.442057 26 | 24 0.001272 0.40803 27 | 25 0.222 1.042 28 | 26 -0.115772 0.162604 29 | 27 1.6e-005 0.444362 30 | 28 0.001374 0.40243 31 | 29 0.227 0.996 32 | 30 -0.117188 0.09832299999999999 33 | 31 3e-005 0.531903 34 | 32 0.001122 0.369589 35 | 33 0.228 0.99 36 | 34 -0.12243 0.098658 37 | 35 2.8e-005 0.530092 38 | 36 0.001118 0.370399 39 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/brisque.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/brisque.cpp -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/brisque.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/brisque.h -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/computescore.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/computescore.cpp -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/JPEG2k-compressed.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/JPEG2k-compressed.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/blur-vision.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/blur-vision.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/compressed-heavy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/compressed-heavy.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/noise-version.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/noise-version.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/original-rotated-image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/original-rotated-image.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/original-scaled-image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/images/original-scaled-image.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/COPYRIGHT: -------------------------------------------------------------------------------- 1 | 2 | Copyright (c) 2000-2014 Chih-Chung Chang and Chih-Jen Lin 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions 7 | are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | 16 | 3. Neither name of copyright holders nor the names of its contributors 17 | may be used to endorse or promote products derived from this software 18 | without specific prior written permission. 19 | 20 | 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 24 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR 25 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 26 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 27 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 28 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 29 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 30 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 31 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/Makefile: -------------------------------------------------------------------------------- 1 | CXX ?= g++ 2 | CFLAGS = -Wall -Wconversion -O3 -fPIC 3 | SHVER = 2 4 | OS = $(shell uname) 5 | 6 | all: svm-train svm-predict svm-scale 7 | 8 | lib: svm.o 9 | if [ "$(OS)" = "Darwin" ]; then \ 10 | SHARED_LIB_FLAG="-dynamiclib -Wl,-install_name,libsvm.so.$(SHVER)"; \ 11 | else \ 12 | SHARED_LIB_FLAG="-shared -Wl,-soname,libsvm.so.$(SHVER)"; \ 13 | fi; \ 14 | $(CXX) $${SHARED_LIB_FLAG} svm.o -o libsvm.so.$(SHVER) 15 | 16 | svm-predict: svm-predict.c svm.o 17 | $(CXX) $(CFLAGS) svm-predict.c svm.o -o svm-predict -lm 18 | svm-train: svm-train.c svm.o 19 | $(CXX) $(CFLAGS) svm-train.c svm.o -o svm-train -lm 20 | svm-scale: svm-scale.c 21 | $(CXX) $(CFLAGS) svm-scale.c -o svm-scale 22 | svm.o: svm.cpp svm.h 23 | $(CXX) $(CFLAGS) -c svm.cpp 24 | clean: 25 | rm -f *~ svm.o svm-train svm-predict svm-scale libsvm.so.$(SHVER) 26 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/Makefile.win: -------------------------------------------------------------------------------- 1 | #You must ensure nmake.exe, cl.exe, link.exe are in system path. 2 | #VCVARS64.bat 3 | #Under dosbox prompt 4 | #nmake -f Makefile.win 5 | 6 | ########################################## 7 | CXX = cl.exe 8 | CFLAGS = /nologo /O2 /EHsc /I. /D _WIN64 /D _CRT_SECURE_NO_DEPRECATE 9 | TARGET = windows 10 | 11 | all: $(TARGET)\svm-train.exe $(TARGET)\svm-predict.exe $(TARGET)\svm-scale.exe $(TARGET)\svm-toy.exe lib 12 | 13 | $(TARGET)\svm-predict.exe: svm.h svm-predict.c svm.obj 14 | $(CXX) $(CFLAGS) svm-predict.c svm.obj -Fe$(TARGET)\svm-predict.exe 15 | 16 | $(TARGET)\svm-train.exe: svm.h svm-train.c svm.obj 17 | $(CXX) $(CFLAGS) svm-train.c svm.obj -Fe$(TARGET)\svm-train.exe 18 | 19 | $(TARGET)\svm-scale.exe: svm.h svm-scale.c 20 | $(CXX) $(CFLAGS) svm-scale.c -Fe$(TARGET)\svm-scale.exe 21 | 22 | $(TARGET)\svm-toy.exe: svm.h svm.obj svm-toy\windows\svm-toy.cpp 23 | $(CXX) $(CFLAGS) svm-toy\windows\svm-toy.cpp svm.obj user32.lib gdi32.lib comdlg32.lib -Fe$(TARGET)\svm-toy.exe 24 | 25 | svm.obj: svm.cpp svm.h 26 | $(CXX) $(CFLAGS) -c svm.cpp 27 | 28 | lib: svm.cpp svm.h svm.def 29 | $(CXX) $(CFLAGS) -LD svm.cpp -Fe$(TARGET)\libsvm -link -DEF:svm.def 30 | 31 | clean: 32 | -erase /Q *.obj $(TARGET)\*.exe $(TARGET)\*.dll $(TARGET)\*.exp $(TARGET)\*.lib 33 | 34 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/__init__.py -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/java/Makefile: -------------------------------------------------------------------------------- 1 | .SUFFIXES: .class .java 2 | FILES = libsvm/svm.class libsvm/svm_model.class libsvm/svm_node.class \ 3 | libsvm/svm_parameter.class libsvm/svm_problem.class \ 4 | libsvm/svm_print_interface.class \ 5 | svm_train.class svm_predict.class svm_toy.class svm_scale.class 6 | 7 | #JAVAC = jikes 8 | JAVAC_FLAGS = -target 1.7 -source 1.7 9 | JAVAC = javac 10 | # JAVAC_FLAGS = 11 | export CLASSPATH := .:$(CLASSPATH) 12 | 13 | all: $(FILES) 14 | jar cvf libsvm.jar *.class libsvm/*.class 15 | 16 | .java.class: 17 | $(JAVAC) $(JAVAC_FLAGS) $< 18 | 19 | libsvm/svm.java: libsvm/svm.m4 20 | m4 libsvm/svm.m4 > libsvm/svm.java 21 | 22 | clean: 23 | rm -f libsvm/*.class *.class *.jar libsvm/*~ *~ libsvm/svm.java 24 | 25 | dist: clean all 26 | rm *.class libsvm/*.class 27 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/java/libsvm.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/java/libsvm.jar -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/java/libsvm/svm_model.java: -------------------------------------------------------------------------------- 1 | // 2 | // svm_model 3 | // 4 | package libsvm; 5 | public class svm_model implements java.io.Serializable 6 | { 7 | public svm_parameter param; // parameter 8 | public int nr_class; // number of classes, = 2 in regression/one class svm 9 | public int l; // total #SV 10 | public svm_node[][] SV; // SVs (SV[l]) 11 | public double[][] sv_coef; // coefficients for SVs in decision functions (sv_coef[k-1][l]) 12 | public double[] rho; // constants in decision functions (rho[k*(k-1)/2]) 13 | public double[] probA; // pariwise probability information 14 | public double[] probB; 15 | public int[] sv_indices; // sv_indices[0,...,nSV-1] are values in [1,...,num_traning_data] to indicate SVs in the training set 16 | 17 | // for classification only 18 | 19 | public int[] label; // label of each class (label[k]) 20 | public int[] nSV; // number of SVs for each class (nSV[k]) 21 | // nSV[0] + nSV[1] + ... + nSV[k-1] = l 22 | }; 23 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/java/libsvm/svm_node.java: -------------------------------------------------------------------------------- 1 | package libsvm; 2 | public class svm_node implements java.io.Serializable 3 | { 4 | public int index; 5 | public double value; 6 | } 7 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/java/libsvm/svm_parameter.java: -------------------------------------------------------------------------------- 1 | package libsvm; 2 | public class svm_parameter implements Cloneable,java.io.Serializable 3 | { 4 | /* svm_type */ 5 | public static final int C_SVC = 0; 6 | public static final int NU_SVC = 1; 7 | public static final int ONE_CLASS = 2; 8 | public static final int EPSILON_SVR = 3; 9 | public static final int NU_SVR = 4; 10 | 11 | /* kernel_type */ 12 | public static final int LINEAR = 0; 13 | public static final int POLY = 1; 14 | public static final int RBF = 2; 15 | public static final int SIGMOID = 3; 16 | public static final int PRECOMPUTED = 4; 17 | 18 | public int svm_type; 19 | public int kernel_type; 20 | public int degree; // for poly 21 | public double gamma; // for poly/rbf/sigmoid 22 | public double coef0; // for poly/sigmoid 23 | 24 | // these are for training only 25 | public double cache_size; // in MB 26 | public double eps; // stopping criteria 27 | public double C; // for C_SVC, EPSILON_SVR and NU_SVR 28 | public int nr_weight; // for C_SVC 29 | public int[] weight_label; // for C_SVC 30 | public double[] weight; // for C_SVC 31 | public double nu; // for NU_SVC, ONE_CLASS, and NU_SVR 32 | public double p; // for EPSILON_SVR 33 | public int shrinking; // use the shrinking heuristics 34 | public int probability; // do probability estimates 35 | 36 | public Object clone() 37 | { 38 | try 39 | { 40 | return super.clone(); 41 | } catch (CloneNotSupportedException e) 42 | { 43 | return null; 44 | } 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/java/libsvm/svm_print_interface.java: -------------------------------------------------------------------------------- 1 | package libsvm; 2 | public interface svm_print_interface 3 | { 4 | public void print(String s); 5 | } 6 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/java/libsvm/svm_problem.java: -------------------------------------------------------------------------------- 1 | package libsvm; 2 | public class svm_problem implements java.io.Serializable 3 | { 4 | public int l; 5 | public double[] y; 6 | public svm_node[][] x; 7 | } 8 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/java/test_applet.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/libsvm.so.2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/libsvm.so.2 -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/matlab/Makefile: -------------------------------------------------------------------------------- 1 | # This Makefile is used under Linux 2 | 3 | MATLABDIR ?= /usr/local/matlab 4 | # for Mac 5 | # MATLABDIR ?= /opt/local/matlab 6 | 7 | CXX ?= g++ 8 | #CXX = g++-4.1 9 | CFLAGS = -Wall -Wconversion -O3 -fPIC -I$(MATLABDIR)/extern/include -I.. 10 | 11 | MEX = $(MATLABDIR)/bin/mex 12 | MEX_OPTION = CC="$(CXX)" CXX="$(CXX)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CFLAGS)" 13 | # comment the following line if you use MATLAB on 32-bit computer 14 | MEX_OPTION += -largeArrayDims 15 | MEX_EXT = $(shell $(MATLABDIR)/bin/mexext) 16 | 17 | all: matlab 18 | 19 | matlab: binary 20 | 21 | octave: 22 | @echo "please type make under Octave" 23 | 24 | binary: svmpredict.$(MEX_EXT) svmtrain.$(MEX_EXT) libsvmread.$(MEX_EXT) libsvmwrite.$(MEX_EXT) 25 | 26 | svmpredict.$(MEX_EXT): svmpredict.c ../svm.h ../svm.o svm_model_matlab.o 27 | $(MEX) $(MEX_OPTION) svmpredict.c ../svm.o svm_model_matlab.o 28 | 29 | svmtrain.$(MEX_EXT): svmtrain.c ../svm.h ../svm.o svm_model_matlab.o 30 | $(MEX) $(MEX_OPTION) svmtrain.c ../svm.o svm_model_matlab.o 31 | 32 | libsvmread.$(MEX_EXT): libsvmread.c 33 | $(MEX) $(MEX_OPTION) libsvmread.c 34 | 35 | libsvmwrite.$(MEX_EXT): libsvmwrite.c 36 | $(MEX) $(MEX_OPTION) libsvmwrite.c 37 | 38 | svm_model_matlab.o: svm_model_matlab.c ../svm.h 39 | $(CXX) $(CFLAGS) -c svm_model_matlab.c 40 | 41 | ../svm.o: ../svm.cpp ../svm.h 42 | make -C .. svm.o 43 | 44 | clean: 45 | rm -f *~ *.o *.mex* *.obj ../svm.o 46 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/matlab/make.m: -------------------------------------------------------------------------------- 1 | % This make.m is for MATLAB and OCTAVE under Windows, Mac, and Unix 2 | function make() 3 | try 4 | % This part is for OCTAVE 5 | if (exist ('OCTAVE_VERSION', 'builtin')) 6 | mex libsvmread.c 7 | mex libsvmwrite.c 8 | mex -I.. svmtrain.c ../svm.cpp svm_model_matlab.c 9 | mex -I.. svmpredict.c ../svm.cpp svm_model_matlab.c 10 | % This part is for MATLAB 11 | % Add -largeArrayDims on 64-bit machines of MATLAB 12 | else 13 | mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmread.c 14 | mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmwrite.c 15 | mex CFLAGS="\$CFLAGS -std=c99" -I.. -largeArrayDims svmtrain.c ../svm.cpp svm_model_matlab.c 16 | mex CFLAGS="\$CFLAGS -std=c99" -I.. -largeArrayDims svmpredict.c ../svm.cpp svm_model_matlab.c 17 | end 18 | catch err 19 | fprintf('Error: %s failed (line %d)\n', err.stack(1).file, err.stack(1).line); 20 | disp(err.message); 21 | fprintf('=> Please check README for detailed instructions.\n'); 22 | end 23 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/matlab/svm_model_matlab.h: -------------------------------------------------------------------------------- 1 | const char *model_to_matlab_structure(mxArray *plhs[], int num_of_feature, struct svm_model *model); 2 | struct svm_model *matlab_matrix_to_model(const mxArray *matlab_struct, const char **error_message); 3 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/Makefile: -------------------------------------------------------------------------------- 1 | all = lib 2 | 3 | lib: 4 | make -C .. lib 5 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__init__.py -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__pycache__/svm.cpython-35.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__pycache__/svm.cpython-35.pyc -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__pycache__/svm.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__pycache__/svm.cpython-36.pyc -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__pycache__/svmutil.cpython-35.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__pycache__/svmutil.cpython-35.pyc -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__pycache__/svmutil.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/python/__pycache__/svmutil.cpython-36.pyc -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm-predict: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm-predict -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm-scale: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm-scale -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm-toy/gtk/Makefile: -------------------------------------------------------------------------------- 1 | CC? = gcc 2 | CXX? = g++ 3 | CFLAGS = -Wall -O3 -g `pkg-config --cflags gtk+-2.0` 4 | LIBS = `pkg-config --libs gtk+-2.0` 5 | 6 | svm-toy: main.o interface.o callbacks.o ../../svm.o 7 | $(CXX) $(CFLAGS) main.o interface.o callbacks.o ../../svm.o -o svm-toy $(LIBS) 8 | 9 | main.o: main.c 10 | $(CC) $(CFLAGS) -c main.c 11 | 12 | interface.o: interface.c interface.h 13 | $(CC) $(CFLAGS) -c interface.c 14 | 15 | callbacks.o: callbacks.cpp callbacks.h 16 | $(CXX) $(CFLAGS) -c callbacks.cpp 17 | 18 | ../../svm.o: ../../svm.cpp ../../svm.h 19 | make -C ../.. svm.o 20 | 21 | clean: 22 | rm -f *~ callbacks.o svm-toy main.o interface.o callbacks.o ../../svm.o 23 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm-toy/gtk/callbacks.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #ifdef __cplusplus 4 | extern "C" { 5 | #endif 6 | 7 | void 8 | on_window1_destroy (GtkObject *object, 9 | gpointer user_data); 10 | 11 | gboolean 12 | on_draw_main_button_press_event (GtkWidget *widget, 13 | GdkEventButton *event, 14 | gpointer user_data); 15 | 16 | gboolean 17 | on_draw_main_expose_event (GtkWidget *widget, 18 | GdkEventExpose *event, 19 | gpointer user_data); 20 | 21 | void 22 | on_button_change_clicked (GtkButton *button, 23 | gpointer user_data); 24 | 25 | void 26 | on_button_run_clicked (GtkButton *button, 27 | gpointer user_data); 28 | 29 | void 30 | on_button_clear_clicked (GtkButton *button, 31 | gpointer user_data); 32 | 33 | void 34 | on_button_save_clicked (GtkButton *button, 35 | gpointer user_data); 36 | 37 | void 38 | on_button_load_clicked (GtkButton *button, 39 | gpointer user_data); 40 | 41 | void 42 | on_fileselection_destroy (GtkObject *object, 43 | gpointer user_data); 44 | 45 | void 46 | on_filesel_ok_clicked (GtkButton *button, 47 | gpointer user_data); 48 | 49 | void 50 | on_filesel_cancel_clicked (GtkButton *button, 51 | gpointer user_data); 52 | #ifdef __cplusplus 53 | } 54 | #endif 55 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm-toy/gtk/interface.h: -------------------------------------------------------------------------------- 1 | /* 2 | * DO NOT EDIT THIS FILE - it is generated by Glade. 3 | */ 4 | 5 | #ifdef __cplusplus 6 | extern "C" { 7 | #endif 8 | 9 | GtkWidget* create_window (void); 10 | GtkWidget* create_fileselection (void); 11 | 12 | #ifdef __cplusplus 13 | } 14 | #endif 15 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm-toy/gtk/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Initial main.c file generated by Glade. Edit as required. 3 | * Glade will not overwrite this file. 4 | */ 5 | 6 | #include 7 | #include "interface.h" 8 | void svm_toy_initialize(); 9 | 10 | int main (int argc, char *argv[]) 11 | { 12 | GtkWidget *window; 13 | 14 | gtk_set_locale (); 15 | gtk_init (&argc, &argv); 16 | 17 | window = create_window (); 18 | gtk_widget_show (window); 19 | 20 | svm_toy_initialize(); 21 | gtk_main (); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm-toy/qt/Makefile: -------------------------------------------------------------------------------- 1 | CXX? = g++ 2 | INCLUDE = /usr/include/qt4 3 | CFLAGS = -Wall -O3 -I$(INCLUDE) -I$(INCLUDE)/QtGui -I$(INCLUDE)/QtCore 4 | LIB = -lQtGui -lQtCore 5 | MOC = /usr/bin/moc-qt4 6 | 7 | svm-toy: svm-toy.cpp svm-toy.moc ../../svm.o 8 | $(CXX) $(CFLAGS) svm-toy.cpp ../../svm.o -o svm-toy $(LIB) 9 | 10 | svm-toy.moc: svm-toy.cpp 11 | $(MOC) svm-toy.cpp -o svm-toy.moc 12 | 13 | ../../svm.o: ../../svm.cpp ../../svm.h 14 | make -C ../.. svm.o 15 | 16 | clean: 17 | rm -f *~ svm-toy svm-toy.moc ../../svm.o 18 | 19 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm-train: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm-train -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/svm.def: -------------------------------------------------------------------------------- 1 | LIBRARY libsvm 2 | EXPORTS 3 | svm_train @1 4 | svm_cross_validation @2 5 | svm_save_model @3 6 | svm_load_model @4 7 | svm_get_svm_type @5 8 | svm_get_nr_class @6 9 | svm_get_labels @7 10 | svm_get_svr_probability @8 11 | svm_predict_values @9 12 | svm_predict @10 13 | svm_predict_probability @11 14 | svm_free_model_content @12 15 | svm_free_and_destroy_model @13 16 | svm_destroy_param @14 17 | svm_check_parameter @15 18 | svm_check_probability_model @16 19 | svm_set_print_string_function @17 20 | svm_get_sv_indices @18 21 | svm_get_nr_sv @19 22 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/windows/libsvmread.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/windows/libsvmread.mexw64 -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/windows/libsvmwrite.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/windows/libsvmwrite.mexw64 -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/windows/svmpredict.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/windows/svmpredict.mexw64 -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/windows/svmtrain.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/libsvm/windows/svmtrain.mexw64 -------------------------------------------------------------------------------- /ITEM 30-39/ITEM37 OpenCV_BRISQUE/main.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM37 OpenCV_BRISQUE/main.cpp -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/OpenCV_CameraCalibration.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/OpenCV_CameraCalibration.cpp -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/OpenCV_CameraCalibration.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2 4 | import numpy as np 5 | import glob 6 | 7 | # Defining the dimensions of checkerboard 8 | CHECKERBOARD = (6,9) 9 | criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) 10 | 11 | # Creating vector to store vectors of 3D points for each checkerboard image 12 | objpoints = [] 13 | # Creating vector to store vectors of 2D points for each checkerboard image 14 | imgpoints = [] 15 | 16 | 17 | # Defining the world coordinates for 3D points 18 | objp = np.zeros((1, CHECKERBOARD[0]*CHECKERBOARD[1], 3), np.float32) 19 | objp[0,:,:2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2) 20 | prev_img_shape = None 21 | 22 | # Extracting path of individual image stored in a given directory 23 | images = glob.glob('./images/*.jpg') 24 | for fname in images: 25 | img = cv2.imread(fname) 26 | gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 27 | # Find the chess board corners 28 | # If desired number of corners are found in the image then ret = true 29 | ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD, cv2.CALIB_CB_ADAPTIVE_THRESH+ 30 | cv2.CALIB_CB_FAST_CHECK+cv2.CALIB_CB_NORMALIZE_IMAGE) 31 | 32 | """ 33 | If desired number of corner are detected, 34 | we refine the pixel coordinates and display 35 | them on the images of checker board 36 | """ 37 | if ret == True: 38 | objpoints.append(objp) 39 | # refining pixel coordinates for given 2d points. 40 | corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria) 41 | 42 | imgpoints.append(corners2) 43 | 44 | # Draw and display the corners 45 | img = cv2.drawChessboardCorners(img, CHECKERBOARD, corners2,ret) 46 | 47 | #cv2.imshow('img',img) 48 | #cv2.waitKey(0) 49 | 50 | cv2.destroyAllWindows() 51 | 52 | h,w = img.shape[:2] 53 | 54 | """ 55 | Performing camera calibration by 56 | passing the value of known 3D points (objpoints) 57 | and corresponding pixel coordinates of the 58 | detected corners (imgpoints) 59 | """ 60 | ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None) 61 | 62 | print("Camera matrix : \n") 63 | print(mtx) 64 | print("dist : \n") 65 | print(dist) 66 | print("rvecs : \n") 67 | print(rvecs) 68 | print("tvecs : \n") 69 | print(tvecs) 70 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_10.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_10.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_11.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_11.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_12.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_12.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_14.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_14.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_15.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_15.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_18.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_18.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_19.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_19.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_2.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_20.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_20.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_21.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_21.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_22.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_22.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_23.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_23.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_24.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_24.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_25.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_25.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_26.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_26.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_27.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_27.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_29.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_29.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_30.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_30.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_40.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_40.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_41.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_41.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_42.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_42.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_43.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_43.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_44.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_44.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_46.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_46.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_47.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_47.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_48.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_48.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_49.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_49.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_5.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_50.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_50.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_57.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_57.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_6.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_62.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_62.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_64.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_64.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_65.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_65.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_70.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_70.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_71.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_71.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_72.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_72.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_73.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_73.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_75.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_75.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_8.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_9.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM38 OpenCV_CameraCalibration/images/image_9.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM39 OpenCV_ArUco/generate_aruco_markers.cpp: -------------------------------------------------------------------------------- 1 | // 生成aruco标志 2 | #include "pch.h" 3 | #include 4 | #include 5 | 6 | using namespace cv; 7 | 8 | // 用于生成aruco图标 9 | int main() 10 | { 11 | Mat markerImage; 12 | // 生成字典 13 | Ptr dictionary = aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250); 14 | // 生成图像 15 | // 参数分别为字典,第几个标识,图像输出大小为200X200,输出图像,标记边框的宽度 16 | aruco::drawMarker(dictionary, 33, 200, markerImage, 1); 17 | 18 | imwrite("marker33.png", markerImage); 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /ITEM 30-39/ITEM39 OpenCV_ArUco/generate_aruco_markers.py: -------------------------------------------------------------------------------- 1 | # 生成aruco标记 2 | 3 | import cv2 as cv 4 | import numpy as np 5 | 6 | 7 | # Load the predefined dictionary 8 | dictionary = cv.aruco.Dictionary_get(cv.aruco.DICT_6X6_250) 9 | 10 | # Generate the marker 11 | markerImage = np.zeros((200, 200), dtype=np.uint8) 12 | markerImage = cv.aruco.drawMarker(dictionary, 33, 200, markerImage, 1) 13 | 14 | cv.imwrite("marker33.png", markerImage) 15 | -------------------------------------------------------------------------------- /ITEM 30-39/ITEM39 OpenCV_ArUco/image/new_scenery.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM39 OpenCV_ArUco/image/new_scenery.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM39 OpenCV_ArUco/image/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM39 OpenCV_ArUco/image/test.jpg -------------------------------------------------------------------------------- /ITEM 30-39/ITEM39 OpenCV_ArUco/video/test.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 30-39/ITEM39 OpenCV_ArUco/video/test.mp4 -------------------------------------------------------------------------------- /ITEM 40-49/ITEM43 OpenCV_Bgsegm/OpenCV_Bgsegm.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM43 OpenCV_Bgsegm/OpenCV_Bgsegm.cpp -------------------------------------------------------------------------------- /ITEM 40-49/ITEM43 OpenCV_Bgsegm/OpenCV_Bgsegm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Aug 12 19:20:56 2020 4 | 5 | @author: luohenyueji 6 | """ 7 | 8 | import cv2 9 | from time import * 10 | 11 | # TODO 背景减除算法集合 12 | ALGORITHMS_TO_EVALUATE = [ 13 | (cv2.bgsegm.createBackgroundSubtractorGMG(20, 0.7), 'GMG'), 14 | (cv2.bgsegm.createBackgroundSubtractorCNT(), 'CNT'), 15 | (cv2.createBackgroundSubtractorKNN(), 'KNN'), 16 | (cv2.bgsegm.createBackgroundSubtractorMOG(), 'MOG'), 17 | (cv2.createBackgroundSubtractorMOG2(), 'MOG2'), 18 | (cv2.bgsegm.createBackgroundSubtractorGSOC(), 'GSOC'), 19 | (cv2.bgsegm.createBackgroundSubtractorLSBP(), 'LSBP'), 20 | ] 21 | 22 | 23 | # TODO 主函数 24 | def main(): 25 | # 背景分割识别器序号 26 | algo_index = 0 27 | subtractor = ALGORITHMS_TO_EVALUATE[algo_index][0] 28 | videoPath = "./video/vtest.avi" 29 | show_fgmask = False 30 | 31 | # 获得运行环境CPU的核心数 32 | nthreads = cv2.getNumberOfCPUs() 33 | # 设置线程数 34 | cv2.setNumThreads(nthreads) 35 | 36 | # 读取视频 37 | capture = cv2.VideoCapture(videoPath) 38 | 39 | # 当前帧数 40 | frame_num = 0 41 | # 总执行时间 42 | sum_Time = 0.0 43 | 44 | while True: 45 | ret, frame = capture.read() 46 | if not ret: 47 | return 48 | begin_time = time() 49 | fgmask = subtractor.apply(frame) 50 | end_time = time() 51 | run_time = end_time - begin_time 52 | sum_Time = sum_Time + run_time 53 | # 平均执行时间 54 | average_Time = sum_Time / (frame_num + 1) 55 | 56 | if show_fgmask: 57 | segm = fgmask 58 | else: 59 | segm = (frame * 0.5).astype('uint8') 60 | cv2.add(frame, (100, 100, 0, 0), segm, fgmask) 61 | 62 | # 显示当前方法 63 | cv2.putText(segm, ALGORITHMS_TO_EVALUATE[algo_index][1], (10, 30), cv2.FONT_HERSHEY_PLAIN, 2.0, (255, 0, 255), 64 | 2, 65 | cv2.LINE_AA) 66 | # 显示当前线程数 67 | cv2.putText(segm, str(nthreads) + " threads", (10, 60), cv2.FONT_HERSHEY_PLAIN, 2.0, (255, 0, 255), 2, 68 | cv2.LINE_AA) 69 | # 显示当前每帧执行时间 70 | cv2.putText(segm, "averageTime {} s".format(average_Time), (10, 90), cv2.FONT_HERSHEY_PLAIN, 2.0, 71 | (255, 0, 255), 2, cv2.LINE_AA); 72 | 73 | cv2.imshow('some', segm) 74 | key = cv2.waitKey(1) & 0xFF 75 | frame_num = frame_num + 1 76 | 77 | # 按'q'健退出循环 78 | if key == ord('q'): 79 | break 80 | 81 | cv2.destroyAllWindows() 82 | 83 | 84 | if __name__ == '__main__': 85 | main() 86 | -------------------------------------------------------------------------------- /ITEM 40-49/ITEM43 OpenCV_Bgsegm/video/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/opencv/opencv/blob/master/samples/data/vtest.avi -------------------------------------------------------------------------------- /ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres.cpp -------------------------------------------------------------------------------- /ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Aug 20 20:08:22 2020 4 | 5 | @author: luohenyueji 6 | 图像超分放大单输出 7 | """ 8 | 9 | 10 | import cv2 11 | from cv2 import dnn_superres 12 | 13 | def main(): 14 | img_path = "./image/image.png" 15 | # 可选择算法,bilinear, bicubic, edsr, espcn, fsrcnn or lapsrn 16 | algorithm = "bilinear" 17 | # 放大比例,可输入值2,3,4 18 | scale = 4 19 | # 模型路径 20 | path = "./model/LapSRN_x4.pb" 21 | 22 | # 载入图像 23 | img = cv2.imread(img_path) 24 | # 如果输入的图像为空 25 | if img is None: 26 | print("Couldn't load image: " + str(img_path)) 27 | return 28 | 29 | original_img = img.copy() 30 | 31 | # 创建模型 32 | sr = dnn_superres.DnnSuperResImpl_create() 33 | 34 | if algorithm == "bilinear": 35 | img_new = cv2.resize(img, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR) 36 | elif algorithm == "bicubic": 37 | img_new = cv2.resize(img, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC) 38 | elif algorithm == "edsr" or algorithm == "espcn" or algorithm == "fsrcnn" or algorithm == "lapsrn": 39 | # 读取模型 40 | sr.readModel(path) 41 | # 设定算法和放大比例 42 | sr.setModel(algorithm, scale) 43 | # 放大图像 44 | img_new = sr.upsample(img) 45 | else: 46 | print("Algorithm not recognized") 47 | 48 | # 如果失败 49 | if img_new is None: 50 | print("Upsampling failed") 51 | 52 | print("Upsampling succeeded. \n") 53 | 54 | # Display 55 | # 展示图片 56 | cv2.namedWindow("Initial Image", cv2.WINDOW_AUTOSIZE) 57 | # 初始化图片 58 | cv2.imshow("Initial Image", img_new) 59 | cv2.imwrite("./saved.jpg", img_new) 60 | cv2.waitKey(0) 61 | 62 | 63 | if __name__ == '__main__': 64 | main() 65 | -------------------------------------------------------------------------------- /ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres_benchmark_quality.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres_benchmark_quality.cpp -------------------------------------------------------------------------------- /ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres_benchmark_time.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres_benchmark_time.cpp -------------------------------------------------------------------------------- /ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres_multioutput.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres_multioutput.cpp -------------------------------------------------------------------------------- /ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres_video.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres_video.cpp -------------------------------------------------------------------------------- /ITEM 40-49/ITEM44 OpenCV_ImageSuperres/dnn_superres_video.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Aug 20 21:08:22 2020 4 | 5 | @author: luohenyueji 6 | 视频超分放大 7 | """ 8 | import cv2 9 | 10 | from cv2 import dnn_superres 11 | 12 | 13 | def main(): 14 | input_path = "./video/chaplin.mp4" 15 | output_path = "./video/out_chaplin.mp4" 16 | # 选择模型 edsr, espcn, fsrcnn or lapsrn 17 | algorithm = "lapsrn" 18 | # 放大比例,2,3,4,8,根据模型结构选择 19 | scale = 2 20 | # 模型路径 21 | path = "./model/LapSRN_x2.pb" 22 | 23 | # 打开视频 24 | input_video = cv2.VideoCapture(input_path) 25 | # 输入图像编码尺寸 26 | 27 | ex = int(input_video.get(cv2.CAP_PROP_FOURCC)) 28 | 29 | # 获得输出视频图像尺寸 30 | # 如果视频没有打开 31 | if input_video is None: 32 | print("Could not open the video.") 33 | return 34 | 35 | S = ( 36 | int(input_video.get(cv2.CAP_PROP_FRAME_WIDTH)) * scale, int(input_video.get(cv2.CAP_PROP_FRAME_HEIGHT)) * scale) 37 | 38 | output_video = cv2.VideoWriter(output_path, ex, input_video.get(cv2.CAP_PROP_FPS), S, True) 39 | 40 | # 读取超分放大模型 41 | sr = dnn_superres.DnnSuperResImpl_create() 42 | sr.readModel(path) 43 | sr.setModel(algorithm, scale) 44 | 45 | while True: 46 | ret, frame = input_video.read() # 捕获一帧图像 47 | 48 | if not ret: 49 | print("read video error") 50 | return 51 | # 上采样图像 52 | output_frame = sr.upsample(frame) 53 | output_video.write(output_frame) 54 | 55 | cv2.namedWindow("Upsampled video", cv2.WINDOW_AUTOSIZE); 56 | cv2.imshow("Upsampled video", output_frame) 57 | 58 | cv2.namedWindow("Original video", cv2.WINDOW_AUTOSIZE); 59 | cv2.imshow("Original video", frame) 60 | 61 | c = cv2.waitKey(1); 62 | # esc退出 63 | if 27 == c: 64 | break 65 | 66 | input_video.release() 67 | output_video.release() 68 | 69 | 70 | if __name__ == '__main__': 71 | main() 72 | -------------------------------------------------------------------------------- /ITEM 40-49/ITEM44 OpenCV_ImageSuperres/image/butterfly.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM44 OpenCV_ImageSuperres/image/butterfly.png -------------------------------------------------------------------------------- /ITEM 40-49/ITEM44 OpenCV_ImageSuperres/image/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM44 OpenCV_ImageSuperres/image/image.png -------------------------------------------------------------------------------- /ITEM 40-49/ITEM45 OpenCV_ImgHash/OpenCV_ImgHash.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM45 OpenCV_ImgHash/OpenCV_ImgHash.cpp -------------------------------------------------------------------------------- /ITEM 40-49/ITEM45 OpenCV_ImgHash/OpenCV_ImgHash.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Aug 27 19:03:21 2020 4 | 5 | @author: luohenyueji 6 | """ 7 | 8 | import cv2 9 | 10 | 11 | def test_one(title, a, b): 12 | # 创建类 13 | if "AverageHash" == title: 14 | hashFun = cv2.img_hash.AverageHash_create() 15 | elif "PHash" == title: 16 | hashFun = cv2.img_hash.PHash_create() 17 | elif "MarrHildrethHash" == title: 18 | hashFun = cv2.img_hash.MarrHildrethHash_create() 19 | elif "RadialVarianceHash" == title: 20 | hashFun = cv2.img_hash.RadialVarianceHash_create() 21 | elif "BlockMeanHash" == title: 22 | hashFun = cv2.img_hash.BlockMeanHash_create() 23 | elif "ColorMomentHash" == title: 24 | hashFun = cv2.img_hash.ColorMomentHash_create() 25 | 26 | tick = cv2.TickMeter() 27 | print("=== " + title + " ===") 28 | 29 | tick.reset() 30 | tick.start() 31 | # # 计算图a的哈希值 32 | hashA = hashFun.compute(a) 33 | tick.stop() 34 | print("compute1: " + str(tick.getTimeMilli()) + " ms") 35 | 36 | tick.reset() 37 | tick.start() 38 | # 计算图b的哈希值 39 | hashB = hashFun.compute(b) 40 | tick.stop() 41 | print("compute2: " + str(tick.getTimeMilli()) + " ms") 42 | # 比较两张图像哈希值的距离 43 | print("compare: " + str(hashFun.compare(hashA, hashB))) 44 | 45 | 46 | def main(): 47 | inputImg = cv2.imread("./image/img1.jpg") 48 | targetImg = cv2.imread("./image/img4.jpg") 49 | 50 | if inputImg is None or targetImg is None: 51 | print("check input image") 52 | return 53 | 54 | test_one("AverageHash", inputImg, targetImg) 55 | test_one("PHash", inputImg, targetImg) 56 | test_one("MarrHildrethHash", inputImg, targetImg) 57 | test_one("RadialVarianceHash", inputImg, targetImg) 58 | test_one("BlockMeanHash", inputImg, targetImg) 59 | test_one("ColorMomentHash", inputImg, targetImg) 60 | 61 | 62 | if __name__ == '__main__': 63 | main() 64 | -------------------------------------------------------------------------------- /ITEM 40-49/ITEM45 OpenCV_ImgHash/image/img1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM45 OpenCV_ImgHash/image/img1.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM45 OpenCV_ImgHash/image/img2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM45 OpenCV_ImgHash/image/img2.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM45 OpenCV_ImgHash/image/img3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM45 OpenCV_ImgHash/image/img3.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM45 OpenCV_ImgHash/image/img4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM45 OpenCV_ImgHash/image/img4.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM46 OpenCV_IntensityTransform/OpenCV_IntensityTransform.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM46 OpenCV_IntensityTransform/OpenCV_IntensityTransform.cpp -------------------------------------------------------------------------------- /ITEM 40-49/ITEM46 OpenCV_IntensityTransform/image/car.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM46 OpenCV_IntensityTransform/image/car.png -------------------------------------------------------------------------------- /ITEM 40-49/ITEM46 OpenCV_IntensityTransform/image/indicator.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM46 OpenCV_IntensityTransform/image/indicator.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM46 OpenCV_IntensityTransform/image/tree.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM46 OpenCV_IntensityTransform/image/tree.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM46 OpenCV_IntensityTransform/image/xray.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM46 OpenCV_IntensityTransform/image/xray.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8HSV.idx.yml.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8HSV.idx.yml.gz -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8HSV.wS1.yml.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8HSV.wS1.yml.gz -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8HSV.wS2.yml.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8HSV.wS2.yml.gz -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8I.idx.yml.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8I.idx.yml.gz -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8I.wS1.yml.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8I.wS1.yml.gz -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8I.wS2.yml.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8I.wS2.yml.gz -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8MAXBGR.idx.yml.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8MAXBGR.idx.yml.gz -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8MAXBGR.wS1.yml.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8MAXBGR.wS1.yml.gz -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8MAXBGR.wS2.yml.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM47 OpenCV_SaliencyObject/ObjectnessTrainedModel/ObjNessB2W8MAXBGR.wS2.yml.gz -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/OpenCV_SaliencyObject.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM47 OpenCV_SaliencyObject/OpenCV_SaliencyObject.cpp -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/video/dog.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM47 OpenCV_SaliencyObject/video/dog.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM47 OpenCV_SaliencyObject/video/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/opencv/opencv/blob/master/samples/data/vtest.avi -------------------------------------------------------------------------------- /ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/blur-vision.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/blur-vision.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/cut-blur-vision.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/cut-blur-vision.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/cut-noise-version.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/cut-noise-version.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/cut-original-rotated-image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/cut-original-rotated-image.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/noise-version.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/noise-version.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/original-rotated-image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM48 OpenCV_ImageQuality/image/original-rotated-image.jpg -------------------------------------------------------------------------------- /ITEM 40-49/ITEM48 OpenCV_ImageQuality/model/brisque_range_live.yml: -------------------------------------------------------------------------------- 1 | %YAML:1.0 2 | --- 3 | range: !!opencv-matrix 4 | rows: 2 5 | cols: 36 6 | dt: f 7 | data: [ 3.44000012e-01, 1.92631185e-02, 2.31999993e-01, 8 | -1.25608176e-01, 1.54766443e-04, 5.36677078e-04, 2.47999996e-01, 9 | -1.25662684e-01, 1.56631286e-04, 5.32896898e-04, 2.64999986e-01, 10 | -1.37013525e-01, 1.69135848e-04, 3.88529879e-04, 2.68999994e-01, 11 | -1.45002097e-01, 1.74277433e-04, 4.11326590e-04, 4.09000009e-01, 12 | 1.65343825e-02, 2.17999995e-01, -2.00738415e-01, 1.03299266e-04, 13 | 8.17875145e-04, 2.28000000e-01, -1.98958635e-01, 1.15834941e-04, 14 | 8.49922828e-04, 2.46000007e-01, -1.55001476e-01, 1.20401361e-04, 15 | 3.38587241e-04, 2.47999996e-01, -1.48134664e-01, 1.16321200e-04, 16 | 3.34327371e-04, 10., 8.07274520e-01, 1.64100003e+00, 17 | 2.02751741e-01, 7.14265108e-01, 4.68011886e-01, 1.63699996e+00, 18 | 1.79955900e-01, 7.12509930e-01, 4.68246639e-01, 1.54499996e+00, 19 | 1.01060480e-01, 6.86503410e-01, 5.31757474e-01, 1.54900002e+00, 20 | 1.00678936e-01, 6.87403798e-01, 5.33775926e-01, 3.73600006e+00, 21 | 8.01105976e-01, 1.10699999e+00, 1.75127238e-01, 7.52403796e-01, 22 | 4.00098890e-01, 1.09300005e+00, 1.56139076e-01, 7.52328634e-01, 23 | 4.06460851e-01, 1.04900002e+00, 9.35277343e-02, 6.23002231e-01, 24 | 5.31899512e-01, 1.05200005e+00, 9.37106311e-02, 6.25087202e-01, 25 | 5.38609207e-01 ] 26 | -------------------------------------------------------------------------------- /ITEM 40-49/ITEM49 OpenCV_StereoDisparity/OpenCV_StereoDisparity.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM49 OpenCV_StereoDisparity/OpenCV_StereoDisparity.cpp -------------------------------------------------------------------------------- /ITEM 40-49/ITEM49 OpenCV_StereoDisparity/OpenCV_StereoDisparity.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import numpy as np 4 | import cv2 5 | 6 | 7 | # ----- 读图 8 | imgL = cv2.imread("images/im0.png",1) 9 | imgL = cv2.resize(imgL,(600,600)) 10 | 11 | imgR = cv2.imread("images/im1.png",1) 12 | imgR = cv2.resize(imgR,(600,600)) 13 | 14 | # Setting parameters for StereoSGBM algorithm 15 | # 设置 StereoSGBM相关参数 16 | minDisparity = 0 17 | numDisparities = 64 18 | blockSize = 8 19 | disp12MaxDiff = 1 20 | uniquenessRatio = 10 21 | speckleWindowSize = 10 22 | speckleRange = 8 23 | 24 | # Creating an object of StereoSGBM algorithm 25 | # 创建StereoSGBM对象 26 | stereo = cv2.StereoSGBM_create(minDisparity = minDisparity, 27 | numDisparities = numDisparities, 28 | blockSize = blockSize, 29 | disp12MaxDiff = disp12MaxDiff, 30 | uniquenessRatio = uniquenessRatio, 31 | speckleWindowSize = speckleWindowSize, 32 | speckleRange = speckleRange 33 | ) 34 | 35 | # Calculating disparith using the StereoSGBM algorithm 36 | # 计算视差 37 | disp = stereo.compute(imgL, imgR).astype(np.float32) 38 | 39 | # 结果归一化 40 | disp = cv2.normalize(disp,0,255,cv2.NORM_MINMAX) 41 | 42 | # Displaying the disparity map 43 | # 显示结果 44 | cv2.imshow("disparity",disp) 45 | cv2.imshow("left image",imgL) 46 | cv2.imshow("right image",imgR) 47 | cv2.waitKey(0) 48 | 49 | cv2.destroyAllWindows() 50 | -------------------------------------------------------------------------------- /ITEM 40-49/ITEM49 OpenCV_StereoDisparity/images/im0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM49 OpenCV_StereoDisparity/images/im0.png -------------------------------------------------------------------------------- /ITEM 40-49/ITEM49 OpenCV_StereoDisparity/images/im1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 40-49/ITEM49 OpenCV_StereoDisparity/images/im1.png -------------------------------------------------------------------------------- /ITEM 50-59/ITEM50 OpenCV_StereoCamera/calibrate.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 50-59/ITEM50 OpenCV_StereoCamera/calibrate.cpp -------------------------------------------------------------------------------- /ITEM 50-59/ITEM50 OpenCV_StereoCamera/data/download.txt: -------------------------------------------------------------------------------- 1 | https://github.com/luohenyueji/OpenCV-ML-Model/blob/master/OpenCV-Practical-Exercise-Model/50OpenCV_StereoCamera.rar 2 | 3 | or: 4 | https://learnopencv.com/making-a-low-cost-stereo-camera-using-opencv/ -------------------------------------------------------------------------------- /ITEM 50-59/ITEM50 OpenCV_StereoCamera/movie3d.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 50-59/ITEM50 OpenCV_StereoCamera/movie3d.cpp -------------------------------------------------------------------------------- /ITEM 50-59/ITEM50 OpenCV_StereoCamera/movie3d.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | 4 | CamL_id = "data/stereoL.mp4" 5 | CamR_id = "data/stereoR.mp4" 6 | 7 | CamL = cv2.VideoCapture(CamL_id) 8 | CamR = cv2.VideoCapture(CamR_id) 9 | 10 | print("Reading parameters ......") 11 | cv_file = cv2.FileStorage("data/params_py.xml", cv2.FILE_STORAGE_READ) 12 | 13 | Left_Stereo_Map_x = cv_file.getNode("Left_Stereo_Map_x").mat() 14 | Left_Stereo_Map_y = cv_file.getNode("Left_Stereo_Map_y").mat() 15 | Right_Stereo_Map_x = cv_file.getNode("Right_Stereo_Map_x").mat() 16 | Right_Stereo_Map_y = cv_file.getNode("Right_Stereo_Map_y").mat() 17 | cv_file.release() 18 | 19 | while True: 20 | retR, imgR = CamR.read() 21 | retL, imgL = CamL.read() 22 | 23 | if retL and retR: 24 | imgR_gray = cv2.cvtColor(imgR, cv2.COLOR_BGR2GRAY) 25 | imgL_gray = cv2.cvtColor(imgL, cv2.COLOR_BGR2GRAY) 26 | 27 | Left_nice = cv2.remap(imgL, Left_Stereo_Map_x, Left_Stereo_Map_y, cv2.INTER_LANCZOS4, cv2.BORDER_CONSTANT, 0) 28 | Right_nice = cv2.remap(imgR, Right_Stereo_Map_x, Right_Stereo_Map_y, cv2.INTER_LANCZOS4, cv2.BORDER_CONSTANT, 0) 29 | 30 | output = Right_nice.copy() 31 | output[:, :, 0] = Right_nice[:, :, 0] 32 | output[:, :, 1] = Right_nice[:, :, 1] 33 | output[:, :, 2] = Left_nice[:, :, 2] 34 | 35 | # output = Left_nice+Right_nice 36 | output = cv2.resize(output, (700, 700)) 37 | cv2.namedWindow("3D movie", cv2.WINDOW_NORMAL) 38 | cv2.resizeWindow("3D movie", 700, 700) 39 | cv2.imshow("3D movie", output) 40 | 41 | cv2.waitKey(1) 42 | 43 | else: 44 | break 45 | -------------------------------------------------------------------------------- /ITEM 50-59/ITEM51 OpenCV_Polar/OpenCV_Polar.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 50-59/ITEM51 OpenCV_Polar/OpenCV_Polar.cpp -------------------------------------------------------------------------------- /ITEM 50-59/ITEM51 OpenCV_Polar/OpenCV_WarpPolar.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 50-59/ITEM51 OpenCV_Polar/OpenCV_WarpPolar.cpp -------------------------------------------------------------------------------- /ITEM 50-59/ITEM51 OpenCV_Polar/OpenCV_WarpPolar.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | 4 | # ----- 主函数 5 | def main(): 6 | # INTER_LINEAR 双线性插值,WARP_FILL_OUTLIERS填充所有目标图像像素 7 | flags = cv2.INTER_LINEAR | cv2.WARP_FILL_OUTLIERS 8 | # 读图 9 | imagepath = "image/clock.jpg" 10 | src = cv2.imread(imagepath) 11 | if src is None: 12 | print("Could not initialize capturing...\n") 13 | return -1 14 | 15 | # 圆心坐标 16 | center = (float(src.shape[0] / 2), float(src.shape[1] / 2)) 17 | # 圆的半径 18 | maxRadius = min(center[0], center[1]) 19 | 20 | # direct transform 21 | # linear Polar 极坐标变换, None表示OpenCV根据输入自行决定输出图像尺寸 22 | lin_polar_img = cv2.warpPolar(src, None, center, maxRadius, flags) 23 | # semilog Polar 半对数极坐标变换, None表示OpenCV根据输入自行决定输出图像尺寸 24 | log_polar_img = cv2.warpPolar(src, None, center, maxRadius, flags | cv2.WARP_POLAR_LOG) 25 | # inverse transform 逆变换 26 | recovered_lin_polar_img = cv2.warpPolar(lin_polar_img, (src.shape[0], src.shape[1]), center, maxRadius, 27 | flags | cv2.WARP_INVERSE_MAP) 28 | recovered_log_polar = cv2.warpPolar(log_polar_img, (src.shape[0], src.shape[1]), center, maxRadius, 29 | flags | cv2.WARP_POLAR_LOG | cv2.WARP_INVERSE_MAP) 30 | 31 | # 改变结果方向 32 | # lin_polar_img = cv2.rotate(lin_polar_img, cv2.ROTATE_90_CLOCKWISE) 33 | 34 | # 展示图片 35 | cv2.imshow("Src frame", src) 36 | cv2.imshow("Log-Polar", log_polar_img) 37 | cv2.imshow("Linear-Polar", lin_polar_img) 38 | cv2.imshow("Recovered Linear-Polar", recovered_lin_polar_img) 39 | cv2.imshow("Recovered Log-Polar", recovered_log_polar) 40 | cv2.waitKey(0) 41 | return 0 42 | 43 | 44 | if __name__ == '__main__': 45 | main() 46 | -------------------------------------------------------------------------------- /ITEM 50-59/ITEM51 OpenCV_Polar/image/clock.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 50-59/ITEM51 OpenCV_Polar/image/clock.jpg -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/1calcHist_use.cpp: -------------------------------------------------------------------------------- 1 | #include "opencv2/highgui.hpp" 2 | #include "opencv2/imgcodecs.hpp" 3 | #include "opencv2/imgproc.hpp" 4 | #include 5 | using namespace std; 6 | using namespace cv; 7 | 8 | int main() 9 | { 10 | auto imgpath = "image/lena.jpg"; 11 | // 读取彩色图片 12 | Mat src = imread(imgpath, IMREAD_COLOR); 13 | if (src.empty()) 14 | { 15 | return -1; 16 | } 17 | vector bgr_planes; 18 | // 图像RGB颜色通道分离 19 | split(src, bgr_planes); 20 | // 将直方图像素值分为多少个区间/直方图有多少根柱子 21 | int histSize = 256; 22 | // 256不会被使用 23 | float range[] = { 0, 256 }; 24 | const float* histRange = { range }; 25 | // 一些默认参数,一般不变 26 | bool uniform = true, accumulate = false; 27 | Mat b_hist, g_hist, r_hist; 28 | // 参数依次为: 29 | // 输入图像: &bgr_planes[0] 30 | // 输入图像个数:1 31 | // 使用输入图像的第几个通道:0 32 | // 掩膜:Mat() 33 | // 直方图计算结果:b_hist,b_hist存储histSize个区间的像素值个数 34 | // 直方图维度:1 35 | // 直方图像素值范围分为多少区间(直方图条形个数):256 36 | // 是否对得到的直方图数组进行归一化处理;uniform 37 | // 当输入多个图像时,是否累积计算像素值的个数accumulate 38 | calcHist(&bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate); 39 | calcHist(&bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate); 40 | calcHist(&bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate); 41 | 42 | // b_hist表示每个像素范围的像素值个数,其总和等于输入图像长乘宽。 43 | // 如果要统计每个像素范围的像素值百分比,计算方式如下 44 | // b_hist /= (float)(cv::sum(b_hist)[0]); 45 | // g_hist /= (float)(cv::sum(g_hist)[0]); 46 | // r_hist /= (float)(cv::sum(r_hist)[0]); 47 | 48 | /* 以下的参数都是跟直方图展示有关,c++展示图片不那么容易*/ 49 | // 一些绘图参数 50 | int hist_w = 512, hist_h = 400; 51 | int bin_w = cvRound((double)hist_w / histSize); 52 | // 创建一张黑色背景图像,用于展示直方图绘制结果 53 | Mat histImage(hist_h, hist_w, CV_8UC3, Scalar(0, 0, 0)); 54 | // 将直方图归一化到0到histImage.rows,最后两个参数默认就好。 55 | normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat()); 56 | normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat()); 57 | normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat()); 58 | for (int i = 1; i < histSize; i++) 59 | { 60 | //遍历hist元素(注意hist中是float类型) 61 | // 绘制蓝色分量 62 | line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(b_hist.at(i - 1))), 63 | Point(bin_w*(i), hist_h - cvRound(b_hist.at(i))), 64 | Scalar(255, 0, 0), 2, 8, 0); 65 | // 绘制绿色分量 66 | line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(g_hist.at(i - 1))), 67 | Point(bin_w*(i), hist_h - cvRound(g_hist.at(i))), 68 | Scalar(0, 255, 0), 2, 8, 0); 69 | // 绘制红色分量 70 | line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(r_hist.at(i - 1))), 71 | Point(bin_w*(i), hist_h - cvRound(r_hist.at(i))), 72 | Scalar(0, 0, 255), 2, 8, 0); 73 | } 74 | imshow("src image", src); 75 | imshow("dst image", histImage); 76 | waitKey(0); 77 | destroyAllWindows(); 78 | return 0; 79 | } -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/1calcHist_use.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | 5 | def main(): 6 | imgpath = "image/lena.jpg" 7 | src = cv2.imread(imgpath) 8 | if src is None: 9 | print('Could not open or find the image:', imgpath) 10 | return -1 11 | bgr_planes = cv2.split(src) 12 | histSize = 256 13 | # 256会被排除 14 | histRange = (0, 256) 15 | accumulate = False 16 | b_hist = cv2.calcHist(bgr_planes, [0], None, [ 17 | histSize], histRange, accumulate=accumulate) 18 | g_hist = cv2.calcHist(bgr_planes, [1], None, [ 19 | histSize], histRange, accumulate=accumulate) 20 | r_hist = cv2.calcHist(bgr_planes, [2], None, [ 21 | histSize], histRange, accumulate=accumulate) 22 | 23 | # b_hist表示每个像素范围的像素值个数,其总和等于输入图像长乘宽。 24 | # 如果要统计每个像素范围的像素值百分比,计算方式如下 25 | assert(sum(b_hist) == src.shape[0] *src.shape[1]) 26 | # b_hist /= sum(b_hist) 27 | # g_hist /= sum(g_hist) 28 | # r_hist /= sum(r_hist) 29 | # assert(sum(b_hist) == 1) 30 | 31 | # 以下是绘图代码 32 | hist_w = 512 33 | hist_h = 400 34 | bin_w = int(round(hist_w/histSize)) 35 | histImage = np.zeros((hist_h, hist_w, 3), dtype=np.uint8) 36 | cv2.normalize(b_hist, b_hist, alpha=0, beta=hist_h, 37 | norm_type=cv2.NORM_MINMAX) 38 | cv2.normalize(g_hist, g_hist, alpha=0, beta=hist_h, 39 | norm_type=cv2.NORM_MINMAX) 40 | cv2.normalize(r_hist, r_hist, alpha=0, beta=hist_h, 41 | norm_type=cv2.NORM_MINMAX) 42 | for i in range(1, histSize): 43 | cv2.line(histImage, (bin_w*(i-1), hist_h - int(np.round(b_hist[i-1]))), 44 | (bin_w*(i), hist_h - int(np.round(b_hist[i]))), 45 | (255, 0, 0), thickness=2) 46 | cv2.line(histImage, (bin_w*(i-1), hist_h - int(np.round(g_hist[i-1]))), 47 | (bin_w*(i), hist_h - int(np.round(g_hist[i]))), 48 | (0, 255, 0), thickness=2) 49 | cv2.line(histImage, (bin_w*(i-1), hist_h - int(np.round(r_hist[i-1]))), 50 | (bin_w*(i), hist_h - int(np.round(r_hist[i]))), 51 | (0, 0, 255), thickness=2) 52 | cv2.imshow('src image', src) 53 | cv2.imshow('dst image', histImage) 54 | cv2.waitKey(0) 55 | 56 | cv2.destroyAllWindows() 57 | return 0 58 | 59 | 60 | if __name__ == "__main__": 61 | main() -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/2equalizeHist_use.cpp: -------------------------------------------------------------------------------- 1 | #include "opencv2/imgcodecs.hpp" 2 | #include "opencv2/highgui.hpp" 3 | #include "opencv2/imgproc.hpp" 4 | #include 5 | using namespace cv; 6 | using namespace std; 7 | int main() 8 | { 9 | auto imgpath = "image/lena.jpg"; 10 | // 读取彩色图片 11 | Mat src = imread(imgpath, IMREAD_COLOR); 12 | if (src.empty()) 13 | { 14 | return -1; 15 | } 16 | // 变为灰度图 17 | cvtColor(src, src, COLOR_BGR2GRAY); 18 | Mat dst; 19 | equalizeHist(src, dst); 20 | imshow("src image", src); 21 | imshow("dst Image", dst); 22 | waitKey(0); 23 | destroyAllWindows(); 24 | return 0; 25 | } -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/2equalizeHist_use.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | def main(): 4 | imgpath = "image/lena.jpg" 5 | src = cv2.imread(imgpath) 6 | if src is None: 7 | print('Could not open or find the image:', imgpath) 8 | return -1 9 | src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) 10 | dst = cv2.equalizeHist(src) 11 | cv2.imshow("src image", src) 12 | cv2.imshow("dst image", dst) 13 | cv2.waitKey(0) 14 | cv2.destroyAllWindows() 15 | return 0 16 | 17 | 18 | if __name__ == "__main__": 19 | main() -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/3createCLAHE_use.cpp: -------------------------------------------------------------------------------- 1 | #include "opencv2/imgcodecs.hpp" 2 | #include "opencv2/highgui.hpp" 3 | #include "opencv2/imgproc.hpp" 4 | #include 5 | using namespace cv; 6 | using namespace std; 7 | int main() 8 | { 9 | auto imgpath = "image/lena.jpg"; 10 | // 读取彩色图片 11 | Mat src = imread(imgpath, IMREAD_COLOR); 12 | if (src.empty()) 13 | { 14 | return -1; 15 | } 16 | // 变为灰度图 17 | cvtColor(src, src, COLOR_BGR2GRAY); 18 | Mat dst; 19 | cv::Ptr clahe = cv::createCLAHE(); 20 | // 设置对比度限制阈值 21 | clahe->setClipLimit(2); 22 | // 设置划分网格数量 23 | clahe->setTilesGridSize(cv::Size(16, 16)); 24 | clahe->apply(src, dst); 25 | imshow("src image", src); 26 | imshow("dst Image", dst); 27 | waitKey(0); 28 | destroyAllWindows(); 29 | return 0; 30 | } -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/3createCLAHE_use.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | def main(): 4 | imgpath = "image/lena.jpg" 5 | src = cv2.imread(imgpath) 6 | if src is None: 7 | print('Could not open or find the image:', imgpath) 8 | return -1 9 | src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) 10 | clahe = cv2.createCLAHE(clipLimit=2, tileGridSize=(16, 16)) 11 | dst = clahe.apply(src) 12 | cv2.imshow("src image", src) 13 | cv2.imshow("dst image", dst) 14 | cv2.waitKey(0) 15 | cv2.destroyAllWindows() 16 | return 0 17 | 18 | 19 | if __name__ == "__main__": 20 | main() -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/4equalizeHist_color.cpp: -------------------------------------------------------------------------------- 1 | #include "opencv2/highgui.hpp" 2 | #include "opencv2/imgcodecs.hpp" 3 | #include "opencv2/imgproc.hpp" 4 | #include 5 | using namespace std; 6 | using namespace cv; 7 | 8 | // 颜色通道分别进行均衡化 9 | Mat equalizeHistChannel(const Mat inputImage) 10 | { 11 | // 分离通道 12 | vector channels; 13 | split(inputImage, channels); 14 | 15 | // 各个通道图像进行直方图均衡 16 | equalizeHist(channels[0], channels[0]); 17 | equalizeHist(channels[1], channels[1]); 18 | equalizeHist(channels[2], channels[2]); 19 | 20 | // 合并结果 21 | Mat result; 22 | merge(channels, result); 23 | 24 | return result; 25 | } 26 | 27 | // 仅对亮度通道进行均衡化 28 | Mat equalizeHistIntensity(const Mat inputImage) 29 | { 30 | Mat yuv; 31 | 32 | // 将bgr格式转换为yuv444 33 | cvtColor(inputImage, yuv, COLOR_BGR2YUV); 34 | 35 | vector channels; 36 | split(yuv, channels); 37 | // 均衡化亮度通道 38 | equalizeHist(channels[0], channels[0]); 39 | 40 | Mat result; 41 | merge(channels, yuv); 42 | 43 | cvtColor(yuv, result, COLOR_YUV2BGR); 44 | 45 | return result; 46 | } 47 | 48 | int main() 49 | { 50 | auto imgpath = "image/lena.jpg"; 51 | // 读取彩色图片 52 | Mat src = imread(imgpath, IMREAD_COLOR); 53 | if (src.empty()) 54 | { 55 | return -1; 56 | } 57 | Mat dstChannel, dstIntensity; 58 | dstChannel = equalizeHistChannel(src); 59 | dstIntensity = equalizeHistIntensity(src); 60 | imshow("src image", src); 61 | imshow("dstChannel image", dstChannel); 62 | imshow("dstIntensity image", dstIntensity); 63 | waitKey(0); 64 | destroyAllWindows(); 65 | return 0; 66 | } -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/4equalizeHist_color.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | # 颜色通道分别进行均衡化 4 | def equalizeHistChannel(inputImage): 5 | channels = cv2.split(inputImage) 6 | 7 | # 各个通道图像进行直方图均衡 8 | cv2.equalizeHist(channels[0], channels[0]) 9 | cv2.equalizeHist(channels[1], channels[1]) 10 | cv2.equalizeHist(channels[2], channels[2]) 11 | 12 | # 合并结果 13 | result = cv2.merge(channels) 14 | 15 | return result 16 | 17 | # 仅对亮度通道进行均衡化 18 | def equalizeHistIntensity(inputImage): 19 | # 将bgr格式转换为yuv444 20 | inputImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2YUV) 21 | 22 | channels = cv2.split(inputImage) 23 | # 均衡化亮度通道 24 | cv2.equalizeHist(channels[0], channels[0]) 25 | # 合并结果 26 | result = cv2.merge(channels) 27 | result = cv2.cvtColor(result, cv2.COLOR_YUV2BGR) 28 | 29 | return result 30 | 31 | 32 | def main(): 33 | imgpath = "image/lena.jpg" 34 | src = cv2.imread(imgpath) 35 | if src is None: 36 | print('Could not open or find the image:', imgpath) 37 | return -1 38 | dstChannel = equalizeHistChannel(src) 39 | dstIntensity = equalizeHistIntensity(src) 40 | cv2.imshow("src image", src) 41 | cv2.imshow("dstChannel image", dstChannel) 42 | cv2.imshow("dstIntensity image", dstIntensity) 43 | cv2.waitKey(0) 44 | cv2.destroyAllWindows() 45 | return 0 46 | 47 | 48 | if __name__ == "__main__": 49 | main() -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/5compareHist_use.cpp: -------------------------------------------------------------------------------- 1 | #include "opencv2/imgcodecs.hpp" 2 | #include "opencv2/highgui.hpp" 3 | #include "opencv2/imgproc.hpp" 4 | #include 5 | using namespace std; 6 | using namespace cv; 7 | 8 | int main() 9 | { 10 | string imgs[] = { "image/lena.jpg", "image/lena_resize.jpg", "image/lena_flip.jpg","image/test.jpg" }; 11 | Mat src_base = imread(imgs[0]); 12 | Mat src_test1 = imread(imgs[1]); 13 | Mat src_test2 = imread(imgs[2]); 14 | Mat src_test3 = imread(imgs[3]); 15 | if (src_base.empty() || src_test1.empty() || src_test2.empty() || src_test3.empty()) 16 | { 17 | cout << "Could not open or find the images!\n" << endl; 18 | return -1; 19 | } 20 | // 将图片转换到hsv空间 21 | Mat hsv_base, hsv_test1, hsv_test2, hsv_test3; 22 | cvtColor(src_base, hsv_base, COLOR_BGR2HSV); 23 | cvtColor(src_test1, hsv_test1, COLOR_BGR2HSV); 24 | cvtColor(src_test2, hsv_test2, COLOR_BGR2HSV); 25 | cvtColor(src_test3, hsv_test3, COLOR_BGR2HSV); 26 | int h_bins = 50, s_bins = 60; 27 | int histSize[] = { h_bins, s_bins }; 28 | // hue值变化范围为0到179,saturation值变化范围为0到255 29 | float h_ranges[] = { 0, 180 }; 30 | float s_ranges[] = { 0, 256 }; 31 | const float* ranges[] = { h_ranges, s_ranges }; 32 | // 使用前两个通道计算直方图 33 | int channels[] = { 0, 1 }; 34 | Mat hist_base, hist_half_down, hist_test1, hist_test2, hist_test3; 35 | calcHist(&hsv_base, 1, channels, Mat(), hist_base, 2, histSize, ranges, true, false); 36 | normalize(hist_base, hist_base, 0, 1, NORM_MINMAX, -1, Mat()); 37 | calcHist(&hsv_test1, 1, channels, Mat(), hist_test1, 2, histSize, ranges, true, false); 38 | normalize(hist_test1, hist_test1, 0, 1, NORM_MINMAX, -1, Mat()); 39 | calcHist(&hsv_test2, 1, channels, Mat(), hist_test2, 2, histSize, ranges, true, false); 40 | normalize(hist_test2, hist_test2, 0, 1, NORM_MINMAX, -1, Mat()); 41 | calcHist(&hsv_test3, 1, channels, Mat(), hist_test3, 2, histSize, ranges, true, false); 42 | normalize(hist_test3, hist_test3, 0, 1, NORM_MINMAX, -1, Mat()); 43 | // 可以查看枚举变量HistCompMethods中有多少种compare_method方法; 44 | for (int compare_method = 0; compare_method < 6; compare_method++) 45 | { 46 | // 不同方法的结果表示含义不一样 47 | double base_base = compareHist(hist_base, hist_base, compare_method); 48 | double base_test1 = compareHist(hist_base, hist_test1, compare_method); 49 | double base_test2 = compareHist(hist_base, hist_test2, compare_method); 50 | double base_test3 = compareHist(hist_base, hist_test3, compare_method); 51 | printf("method[%d]: base_base : %.3f \t base_test1: %.3f \t base_test2: %.3f \t base_test3: %.3f \n", compare_method, base_base, base_test1, base_test2, base_test3); 52 | } 53 | printf("Done \n"); 54 | system("pause"); 55 | return 0; 56 | } -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/5compareHist_use.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | def main(): 4 | imgs = ["image/lena.jpg", "image/lena_resize.jpg", "image/lena_flip.jpg","image/test.jpg"] 5 | src_base = cv2.imread(imgs[0]) 6 | src_test1 = cv2.imread(imgs[1]) 7 | src_test2 = cv2.imread(imgs[2]) 8 | src_test3 = cv2.imread(imgs[3]) 9 | if src_base is None or src_test1 is None or src_test2 is None or src_test3 is None: 10 | print('Could not open or find the images!') 11 | exit(0) 12 | # 将图片转换到hsv空间 13 | hsv_base = cv2.cvtColor(src_base, cv2.COLOR_BGR2HSV) 14 | hsv_test1 = cv2.cvtColor(src_test1, cv2.COLOR_BGR2HSV) 15 | hsv_test2 = cv2.cvtColor(src_test2, cv2.COLOR_BGR2HSV) 16 | hsv_test3 = cv2.cvtColor(src_test3, cv2.COLOR_BGR2HSV) 17 | h_bins = 50 18 | s_bins = 60 19 | histSize = [h_bins, s_bins] 20 | # hue值变化范围为0到179,saturation值变化范围为0到255 21 | h_ranges = [0, 180] 22 | s_ranges = [0, 256] 23 | # 合并 24 | ranges = h_ranges + s_ranges 25 | # 使用前两个通道计算直方图 26 | channels = [0, 1] 27 | hist_base = cv2.calcHist([hsv_base], channels, None, 28 | histSize, ranges, accumulate=False) 29 | cv2.normalize(hist_base, hist_base, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX) 30 | hist_test1 = cv2.calcHist([hsv_test1], channels, None, 31 | histSize, ranges, accumulate=False) 32 | cv2.normalize(hist_test1, hist_test1, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX) 33 | hist_test2 = cv2.calcHist([hsv_test2], channels, None, 34 | histSize, ranges, accumulate=False) 35 | cv2.normalize(hist_test2, hist_test2, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX) 36 | hist_test3 = cv2.calcHist([hsv_test3], channels, None, 37 | histSize, ranges, accumulate=False) 38 | cv2.normalize(hist_test3, hist_test3, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX) 39 | for compare_method in range(6): 40 | base_base = cv2.compareHist(hist_base, hist_base, compare_method) 41 | base_test1 = cv2.compareHist(hist_base, hist_test1, compare_method) 42 | base_test2 = cv2.compareHist(hist_base, hist_test2, compare_method) 43 | base_test3 = cv2.compareHist(hist_base, hist_test3, compare_method) 44 | print("method[%s]: base_base : %.3f \t base_test1: %.3f \t base_test2: %.3f \t base_test3: %.3f \n" % ( 45 | compare_method, base_base, base_test1, base_test2, base_test3)) 46 | 47 | print("Done \n") 48 | 49 | if __name__ == "__main__": 50 | main() -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/6calcBackProject_use.cpp: -------------------------------------------------------------------------------- 1 | #include "opencv2/imgproc.hpp" 2 | #include "opencv2/imgcodecs.hpp" 3 | #include "opencv2/highgui.hpp" 4 | #include 5 | using namespace cv; 6 | using namespace std; 7 | int main() 8 | { 9 | // 感兴趣区域图片 10 | string roipath = "image/test3.jpg"; 11 | // 目标图片 12 | string targetpath = "image/test2.jpg"; 13 | Mat target = imread(targetpath); 14 | Mat roi = imread(roipath); 15 | if (target.empty() || roi.empty()) 16 | { 17 | cout << "Could not open or find the images!\n" << endl; 18 | return -1; 19 | } 20 | 21 | Mat hsv, hsvt; 22 | cvtColor(roi, hsv, COLOR_BGR2HSV); 23 | cvtColor(target, hsvt, COLOR_BGR2HSV); 24 | // 使用前两个通道计算直方图 25 | int channels[] = { 0, 1 }; 26 | // 计算颜色直方图 27 | Mat roihist; 28 | int h_bins = 180, s_bins = 256; 29 | int histSize[] = { h_bins, s_bins }; 30 | // hue值变化范围为0到179,saturation值变化范围为0到255 31 | float h_ranges[] = { 0, 180 }; 32 | float s_ranges[] = { 0, 256 }; 33 | const float* ranges[] = { h_ranges, s_ranges }; 34 | calcHist(&hsv, 1, channels, Mat(), roihist, 2, histSize, ranges, true, false); 35 | // 归一化图片 36 | normalize(roihist, roihist, 0, 255, NORM_MINMAX, -1, Mat()); 37 | 38 | // 返回匹配结果图像,dst为一张二值图,白色区域表示匹配到的目标 39 | Mat dst; 40 | calcBackProject(&hsvt, 1, channels, roihist, dst, ranges, 1); 41 | 42 | // 应用线性滤波器,理解成去噪就行了 43 | Mat disc = getStructuringElement(MORPH_ELLIPSE, Size(7, 7)); 44 | filter2D(dst, dst, -1, disc); 45 | 46 | // 阈值过滤 47 | Mat thresh; 48 | threshold(dst, thresh, 50, 255, 0); 49 | 50 | // 将thresh转换为3通道图 51 | Mat thresh_group[3] = { thresh, thresh, thresh }; 52 | cv::merge(thresh_group, 3, thresh); 53 | imwrite("thresh.jpg", thresh); 54 | // 从图片中提取感兴趣区域 55 | Mat res; 56 | bitwise_and(target, thresh, res); 57 | imshow("target", target); 58 | imshow("thresh", thresh); 59 | imshow("res", res); 60 | waitKey(0); 61 | destroyAllWindows(); 62 | return 0; 63 | } -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/6calcBackProject_use.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | 4 | def main(): 5 | # 感兴趣区域图片 6 | roi = cv2.imread('image/test3.jpg') 7 | # 目标图片 8 | target = cv2.imread('image/test2.jpg') 9 | if roi is None or target is None: 10 | print('Could not open or find the images!') 11 | return -1 12 | hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV) 13 | hsvt = cv2.cvtColor(target, cv2.COLOR_BGR2HSV) 14 | # 计算颜色直方图 15 | roihist = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256]) 16 | # 归一化图片 17 | cv2.normalize(roihist, roihist, 0, 255, cv2.NORM_MINMAX) 18 | # 返回匹配结果图像,dst为一张二值图,白色区域表示匹配到的目标 19 | dst = cv2.calcBackProject([hsvt], [0, 1], roihist, [0, 180, 0, 256], 1) 20 | # 应用线性滤波器,理解成去噪就行了 21 | disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)) 22 | cv2.filter2D(dst, -1, disc, dst) 23 | # 阈值过滤 24 | ret, thresh = cv2.threshold(dst, 50, 255, 0) 25 | # 将thresh转换为3通道图 26 | thresh = cv2.merge((thresh, thresh, thresh)) 27 | # 从图片中提取感兴趣区域 28 | res = cv2.bitwise_and(target, thresh) 29 | cv2.imshow("target", target) 30 | cv2.imshow("thresh", thresh) 31 | cv2.imshow("res", res) 32 | cv2.waitKey(0) 33 | cv2.destroyAllWindows() 34 | return 0 35 | 36 | 37 | if __name__ == "__main__": 38 | main() -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/image/lena.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 50-59/ITEM52 OpenCV_Histogram/image/lena.jpg -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/image/lena_flip.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 50-59/ITEM52 OpenCV_Histogram/image/lena_flip.jpg -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/image/lena_resize.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 50-59/ITEM52 OpenCV_Histogram/image/lena_resize.jpg -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/image/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 50-59/ITEM52 OpenCV_Histogram/image/test.jpg -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/image/test2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 50-59/ITEM52 OpenCV_Histogram/image/test2.jpg -------------------------------------------------------------------------------- /ITEM 50-59/ITEM52 OpenCV_Histogram/image/test3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luohenyueji/OpenCV-Practical-Exercise/457366b9437b06a6259dd4e16db012049a530621/ITEM 50-59/ITEM52 OpenCV_Histogram/image/test3.jpg -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 luohenyueji 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | --------------------------------------------------------------------------------