[英]how to change the black pixels in the below image to red pixels using opencv libraries with c++
[英]remove all black pixels and get only required image using C++ (OpenCV)
我試過 findNonZero 和 boundingRect。 但沒有什么能幫助我。 我是 C++ OpenCV 的新手。 I did this using Python OpenCV which involved NumPy, but unfortunately I am not able to do the same in C++.
輸入圖像
Python:
def crop_with_arg(refactor_image):
mask = refactor_image > 0
coord = np.argwhere(mask)
x0, y0 = coord.min(axis=0)
x1, y1 = coord.max(axis=0) + 1
cropped = refactor_image[x0:x1, y0:y1]
return cropped
def crop_image(image_crop, tol=50):
mask = image_crop > tol
return image_crop[np.ix_(mask.any(1), mask.any(0))]
compressed_img = crop_with_arg(gray)
croppped_image = crop_image(compressed_img, tol=50)
我正在編寫目標 C++ 中的代碼,以獲得 iOS 的包裝器。
對於灰度圖像,以下代碼完美運行。
值 50 是可以根據已完成的預處理設置的閾值限制。
grayThres = gray > 50;
graycloned = grayThres.clone();
std::vector<cv::Point> nonBlackList;
nonBlackList.reserve(graycloned.rows*graycloned.cols);
for(int j=0; j<graycloned.rows; ++j)
for(int i=0; i<graycloned.cols; ++i)
{
// if not black: add to the list
if(graycloned.at<cv::Vec2b>(j,i) != cv::Vec2b(0,0))
{
nonBlackList.push_back(cv::Point(j,i));
}
}
// create bounding rect around those points
cv::Rect bb = cv::boundingRect(nonBlackList);
cv:: Mat returnImage = gray(bb);
我認為這樣的事情,使用cv::boundingRect()
會非常有效:
#include <iostream>
#include <opencv2/opencv.hpp>
int
main(int argc,char*argv[])
{
// Load image as greyscale
cv::Mat im = cv::imread("thing.jpg", cv::IMREAD_GRAYSCALE);
// Threshold image at 128
cv::Mat thresh;
cv::threshold(im, thresh, 128, 255, cv::THRESH_BINARY);
// Do the actual work
double t = (double)cv::getTickCount();
cv::Rect ROI = cv::boundingRect(thresh);
t = ((double)cv::getTickCount() - t)/cv::getTickFrequency();
// Print timing and results
std::cout << "Time: " << t*1000.0 << "ms" << std::endl;
std::cout << ROI << std::endl;
}
樣品 Output
Time: 0.317279ms
[253 x 48 from (113, 503)]
順便說一句,您可以使用ImageMagick從命令行更簡單地執行此操作,它包含在大多數 Linux 發行版中,可用於 macOS 和 ZEDC9F0A5A5D57797BF68E37364743831
# Print coordinates of trim-box
convert thing.jpg -threshold 50% -format %@ info:
253x48+113+503
或者,實際上進行修剪:
convert thing.jpg -threshold 50% -trim result.jpg
關鍵詞: 圖像處理, OpenCV, C++, 修剪, 修剪框, 修剪框, 裁剪, 修剪框, 邊框, 邊框, 去除邊框, 修剪邊框, ROI, boundingRect(), cv::boundingRect()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.