{"id":17625,"date":"2022-10-26T07:59:51","date_gmt":"2022-10-26T02:29:51","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/"},"modified":"2022-10-26T07:59:51","modified_gmt":"2022-10-26T02:29:51","slug":"solved-list-of-white-pixels-indices-in-image-using-cuda","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/","title":{"rendered":"[Solved] list of white pixels indices in image using CUDA"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-47457289\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"47457289\" data-parentid=\"47454510\" data-score=\"1\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>Following is a naive method to achieve the desired functionality:<\/p>\n<ul>\n<li>Generate a mask of pixel indices with dummy values for pixel with zero value.<\/li>\n<li>Count the number of non-zero pixels<\/li>\n<li>Create an output vector with length equal to non-zero count.<\/li>\n<li>Copy the non-zero pixel indices from the generated mask to the output vector (a process known as stream-compaction)<\/li>\n<\/ul>\n<p>Following is a sample code for the above mentioned process.<\/p>\n<h1>Code<\/h1>\n<pre><code>#include &lt;cstdio&gt;\n#include &lt;vector&gt;\n#include &lt;cuda_runtime.h&gt;\n#include &lt;thrust\/count.h&gt;\n#include &lt;thrust\/host_vector.h&gt;\n#include &lt;thrust\/device_vector.h&gt;\n#include &lt;thrust\/execution_policy.h&gt;\n#include &lt;opencv2\/opencv.hpp&gt;\n\n\nstatic void _check_err(cudaError_t err, const char* file, int line)\n{\n    if(err)\n    {\n        const char* err_str = cudaGetErrorString(err);\n\n        printf(\"CUDA Error: %s\\nFile: %s\\nLine: %d\\n\", err_str, file, line);\n        exit(EXIT_FAILURE);\n    }\n}\n\n#define CHECK_ERR(err) _check_err((err), __FILE__, __LINE__)\n\n\n\n__global__ void kernel_find_indices(const unsigned char* input, int width, int height, int step, int2* indices)\n{\n    const int x = blockIdx.x * blockDim.x + threadIdx.x;\n    const int y = blockIdx.y * blockDim.y + threadIdx.y;\n\n    if(x &lt; width &amp;&amp; y &lt; height)\n    {\n        const int tidPixel = y * step + x;\n        const int tidIndex = y * width + x;\n\n        unsigned char value = input[tidPixel];\n\n        int2 index_to_write;\n\n\n        if(value)\n        {\n            \/\/Write actual index to pixels with non-zero value\n            index_to_write.x = x;\n            index_to_write.y = y;\n        }\n        else\n        {\n            \/\/Write dummy index to pixels with zero value\n            index_to_write.x = -1;\n            index_to_write.y = -1;\n        }\n\n        indices[tidIndex] = index_to_write;\n    }\n}\n\n\n\/\/Operator to check whether an index is of a non-zero pixel\nstruct isNonZeroIndex\n{\n  __host__ __device__ bool operator()(const int2 &amp;idx)\n  {\n    return (idx.x != -1) &amp;&amp; (idx.y != -1);\n  }\n};\n\n\nstd::vector&lt;cv::Point&gt; getIndicesOfNonZeroPixels(cv::Mat input)\n{\n    std::vector&lt;int2&gt; output_int2;\n    std::vector&lt;cv::Point&gt; output;\n\n    int pixelCount = input.cols * input.rows;\n    size_t imageBytes=  input.step * input.rows;\n\n    unsigned char* image_d;\n    thrust::device_vector&lt;int2&gt; index_buffer_d(pixelCount);\n\n    \/\/Allocate device memory for input image\n    CHECK_ERR(cudaMalloc(&amp;image_d, imageBytes));\n    \/\/Copy input image to device\n    CHECK_ERR(cudaMemcpy(image_d, input.ptr(), imageBytes, cudaMemcpyHostToDevice));\n\n    dim3 block(16,16);\n    dim3 grid;\n    grid.x = (input.cols + block.x - 1) \/ block.x;\n    grid.y = (input.rows + block.y - 1) \/ block.y;\n\n    \/\/Generate an index mask with dummy values for indices with zero pixel value\n    kernel_find_indices&lt;&lt;&lt;grid, block&gt;&gt;&gt;(image_d, input.cols, input.rows, input.step, thrust::raw_pointer_cast(index_buffer_d.data()));\n    CHECK_ERR(cudaDeviceSynchronize());\n\n    int nonZeroCount = thrust::count_if(index_buffer_d.begin(), index_buffer_d.end(), isNonZeroIndex());\n\n    \/\/Keep only those indices whose pixel value is non-zero (stream compaction)\n    thrust::device_vector&lt;int2&gt; compacted(nonZeroCount);\n    thrust::copy_if(index_buffer_d.begin(), index_buffer_d.end(), compacted.begin(), isNonZeroIndex());\n\n    \/\/Copy non-zero pixel indices to host\n    output_int2.resize(nonZeroCount);\n    thrust::copy(compacted.begin(), compacted.end(), output_int2.begin());\n\n    CHECK_ERR(cudaFree(image_d));\n\n    \/\/Convert vector&lt;int2&gt; to vector&lt;cv::Point&gt;\n    output.resize(nonZeroCount);\n    for(size_t i=0; i&lt;nonZeroCount; i++)\n        output[i] = cv::Point(output_int2[i].x, output_int2[i].y);\n\n    return output;\n}\n\nvoid run_test()\n{\n    \/\/Generate a sample test image\n    cv::Mat test = cv::Mat::zeros(100,100, CV_8UC1);\n    cv::rectangle(test, cv::Rect(5,5,20,20), cv::Scalar::all(255), CV_FILLED);\n\n    \/\/Get pixel indices of non-zero pixels\n    std::vector&lt;cv::Point&gt; indices = getIndicesOfNonZeroPixels(test);\n\n    \/\/Display those indices\n    for(size_t i=0; i&lt;indices.size(); i++)\n    {\n        printf(\"%d, %d\\n\", indices[i].x, indices[i].y);\n    }\n\n    \/\/Show image\n    cv::imshow(\"Sample\", test);\n    cv::waitKey();\n}\n\nint main(int argc, char** argv)\n{\n    run_test();\n    return 0;\n}\n<\/code><\/pre>\n<h1>Compilation Command<\/h1>\n<blockquote>\n<p>nvcc -o nz nz.cu -arch=sm_61 -L\/usr\/local\/lib -lopencv_core<br \/>\n  -lopencv_highgui -lopencv_imgproc<\/p>\n<\/blockquote>\n<p>Please keep in mind that this code is for image of type <code>8UC1<\/code> (8 bit, single channel) only. You can easily extend it to other data-types as required.<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">3<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved list of white pixels indices in image using CUDA <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] Following is a naive method to achieve the desired functionality: Generate a mask of pixel indices with dummy values for pixel with zero value. Count the number of non-zero pixels Create an output vector with length equal to non-zero count. Copy the non-zero pixel indices from the generated mask to the output vector (a &#8230; <a title=\"[Solved] list of white pixels indices in image using CUDA\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/\" aria-label=\"More on [Solved] list of white pixels indices in image using CUDA\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[324,1564,881],"class_list":["post-17625","post","type-post","status-publish","format-standard","hentry","category-solved","tag-c","tag-cuda","tag-image-processing"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] list of white pixels indices in image using CUDA - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] list of white pixels indices in image using CUDA - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] Following is a naive method to achieve the desired functionality: Generate a mask of pixel indices with dummy values for pixel with zero value. Count the number of non-zero pixels Create an output vector with length equal to non-zero count. Copy the non-zero pixel indices from the generated mask to the output vector (a ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-10-26T02:29:51+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] list of white pixels indices in image using CUDA\",\"datePublished\":\"2022-10-26T02:29:51+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/\"},\"wordCount\":136,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"c++\",\"cuda\",\"image-processing\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/\",\"name\":\"[Solved] list of white pixels indices in image using CUDA - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-10-26T02:29:51+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] list of white pixels indices in image using CUDA\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] list of white pixels indices in image using CUDA - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] list of white pixels indices in image using CUDA - JassWeb","og_description":"[ad_1] Following is a naive method to achieve the desired functionality: Generate a mask of pixel indices with dummy values for pixel with zero value. Count the number of non-zero pixels Create an output vector with length equal to non-zero count. Copy the non-zero pixel indices from the generated mask to the output vector (a ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/","og_site_name":"JassWeb","article_published_time":"2022-10-26T02:29:51+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] list of white pixels indices in image using CUDA","datePublished":"2022-10-26T02:29:51+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/"},"wordCount":136,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["c++","cuda","image-processing"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/","url":"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/","name":"[Solved] list of white pixels indices in image using CUDA - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-10-26T02:29:51+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-list-of-white-pixels-indices-in-image-using-cuda\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] list of white pixels indices in image using CUDA"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/17625","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=17625"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/17625\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=17625"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=17625"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=17625"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}