Skip to content

Instantly share code, notes, and snippets.

@LaurentBerger
Created February 20, 2019 21:21
Show Gist options
  • Save LaurentBerger/6c885c980131f0ea30aa5bd373624ca2 to your computer and use it in GitHub Desktop.
Save LaurentBerger/6c885c980131f0ea30aa5bd373624ca2 to your computer and use it in GitHub Desktop.
my code :
{
string filename("g:/lib/opencv/samples/data/lena.jpg");
Mat _I = imread(filename.c_str(), IMREAD_COLOR);
cv::Mat I = _I;
if (I.depth())
cv::normalize(I, I, 0., 255., cv::NORM_MINMAX, CV_8U);
if (I.channels() == 3)
{
cv::Mat Lab, tmp;
std::vector<cv::Mat> cns;
cv::cvtColor(I, Lab, cv::COLOR_BGR2Lab);
cv::decolor(Lab, I, tmp);
}
cv::Mat hist;
cv::calcHist(std::vector<cv::Mat>(1, I), { 0 }, cv::noArray(), hist, { 256 }, { 0.f,256.f });
cv::Mat hd;
{
cv::Mat curr = hist.rowRange(0, hist.rows - 1);
cv::Mat next = hist.rowRange(1, hist.rows);
cv::absdiff(next, curr, hd);
}
hd.convertTo(hd, CV_32S);
double thresh = cv::mean(hd)(0);
// cout << utils::iqr(hd)(0);
hd = hd > thresh;
cv::Mat1i idx;
int i = 0;
for (auto it_current = hd.begin<uchar>(), it_next = hd.begin<uchar>() + 1; it_next != hd.end<uchar>(); it_current++, it_next++, i++)
{
uchar current = *it_current;
uchar next = *it_next;
if (current && !next)
idx.push_back(i);
if (!current && next)
idx.push_back(i + 1);
}
std::cout << idx << std::endl;
}
output in c++
[9;
9;
11;
14;
16;
20;
22;
24;
26;
26;
28;
30;
33;
34;
38;
39;
44;
44;
46;
46;
54;
54;
56;
57;
61;
63;
65;
65;
67;
69;
71;
71;
73;
73;
75;
75;
79;
81;
83;
91;
94;
95;
98;
98;
100;
105;
112;
114;
117;
118;
121;
121;
123;
124;
127;
127;
129;
133;
135;
136;
138;
143;
151;
151;
158;
159;
164;
164;
188;
188;
193;
195;
204;
204;
209;
209;
211;
211;
213;
213;
216;
216]
******************************
my python code :
imgpath="g:\\lib\\opencv\\samples\\data\\lena.jpg"
I = cv2.imread(imgpath,cv2.IMREAD_COLOR)
I, _ = cv2.decolor(cv2.cvtColor(I, cv2.COLOR_BGR2Lab))
h = cv2.calcHist([I],[0],None,[256],[0,256]).astype(np.int32).reshape((-1,))
print(h.dtype, I.dtype, I.shape, h.min(), h.max(), I.min(), I.max())
hd = np.abs(np.diff(h))
thresh = np.mean(hd)
print(thresh, np.mean(hd), iqr(hd),flush=True)
hd = hd > thresh
print(hd)
idx = list()
for i in range(254):
if hd[i] and not hd[i+1]:
idx.append(i)
elif not hd[i] and hd[i+1]:
idx.append(i+1)
print(idx)
python output
[9, 9, 11, 14, 16, 20, 22, 24, 26, 26, 28, 30, 33, 34, 38, 39, 44, 44, 46, 46, 54, 54, 56, 57, 61, 63, 65, 65, 67, 69, 71, 71, 73, 73, 75, 75, 79, 81, 83, 91, 94, 95, 98, 98, 100, 105, 112, 114, 117, 118, 121, 121, 123, 124, 127, 127, 129, 133, 135, 136, 138, 143, 151, 151, 158, 159, 164, 164, 188, 188, 193, 195, 204, 204, 209, 209, 211, 211, 213, 213, 216, 216]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment