A different way to visualize classification results

I love good data visualizations. Back in the days when I did my PhD in particle physics, I was stunned by the histograms my colleagues built and how much information was accumulated in one single plot.


Information in Plots

It is really challenging to improve existing visualization methods or to transport methods from other research fields. You have to think about the dimensions in your plot and the ways to add more of them. A good example is the path from a boxplot to a violinplot to a swarmplot. It is a continuous process of adding dimensions and thus information.

The possibilities of adding information or dimensions to a plot are almost endless. Categories can be added with different marker shapes, color maps like in a heat map can serve as another dimension and the size of a marker can give insight to further parameters.

Plots of Classifier Performance

When it comes to machine learning, there are many ways to plot the performance of a classifier. There is an overwhelming amount of metrics to compare different estimators like accuracy, precision, recall or the helpful MMC.

All of the common classification metrics are calculated from true positive, true negative, _false positive _and _false negative _incidents. The most popular plots are definitely ROC curve, PRC, CAP curve and the confusion matrix.

I won’t get into detail of the three curves, but there are many different ways to handle the confusion matrix, like adding a heat map.

A seaborn heatmap of a confusion matrix.

#matplotlib #machine-learning #classification #python #plot

What is GEEK

Buddha Community

A different way to visualize classification results
Connor Mills

Connor Mills

1659063683

HTML, CSS & JavaScript Project: Build Cocktail App

In this tutorial, we will learn how to create a cocktail app with HTML, CSS and Javascript.

Create a cocktail app where the user can search a cocktail of choice and the app displays the ingredients and instructions to make the cocktail. We use 'The Cocktail DB' API to fetch information required for our app.

Project Folder Structure:

Before we start coding let us take look at the project folder structure. We create a project folder called – ‘Cocktail App’. Inside this folder, we have three files. These files are index.html, style.css and script.js.

HTML:

We start with the HTML code. First, copy the code below and paste it into your HTML document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Cocktail App</title>
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div class="search-container">
        <input
          type="text"
          placeholder="Type a cocktail name..."
          id="user-inp"
          value="margarita"
        />
        <button id="search-btn">Search</button>
      </div>
      <div id="result"></div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we style this app using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  height: 100vh;
  background: linear-gradient(#5372f0 50%, #000000 50%);
}
.container {
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  width: 90vw;
  max-width: 37.5em;
  background-color: #ffffff;
  padding: 1.8em;
  border-radius: 0.6em;
  box-shadow: 0 1em 3em rgba(2, 9, 38, 0.25);
}
.search-container {
  display: grid;
  grid-template-columns: 9fr 3fr;
  gap: 1em;
  margin-bottom: 1.2em;
}
.search-container input {
  font-size: 1em;
  padding: 0.6em 0.3em;
  border: none;
  outline: none;
  color: #1f194c;
  border-bottom: 1.5px solid #1f194c;
}
.search-container input:focus {
  border-color: #5372f0;
}
.search-container button {
  font-size: 1em;
  border-radius: 2em;
  background-color: #5372f0;
  border: none;
  outline: none;
  color: #ffffff;
  cursor: pointer;
}
#result {
  color: #575a7b;
  line-height: 2em;
}
#result img {
  display: block;
  max-width: 12.5em;
  margin: auto;
}
#result h2 {
  font-size: 1.25em;
  margin: 0.8em 0 1.6em 0;
  text-align: center;
  text-transform: uppercase;
  font-weight: 600;
  letter-spacing: 0.05em;
  color: #1f194c;
  position: relative;
}
#result h2:before {
  content: "";
  position: absolute;
  width: 15%;
  height: 3px;
  background-color: #5372f0;
  left: 42.5%;
  bottom: -0.3em;
}
#result h3 {
  font-size: 1.1em;
  font-weight: 600;
  margin-bottom: 0.2em;
  color: #1f194c;
}
#result ul {
  margin-bottom: 1em;
  margin-left: 1.8em;
  display: grid;
  grid-template-columns: auto auto;
}
#result li {
  margin-bottom: 0.3em;
}
#result p {
  text-align: justify;
  font-weight: 400;
  font-size: 0.95em;
}
.msg {
  text-align: center;
}
@media screen and (max-width: 600px) {
  .container {
    font-size: 14px;
  }
}

Javascript:

Lastly, we implement the functionality using Javascript. Now copy the code below and paste it into your script file.

let result = document.getElementById("result");
let searchBtn = document.getElementById("search-btn");
let url = "https://thecocktaildb.com/api/json/v1/1/search.php?s=";
let getInfo = () => {
  let userInp = document.getElementById("user-inp").value;
  if (userInp.length == 0) {
    result.innerHTML = `<h3 class="msg">The input field cannot be empty</h3>`;
  } else {
    fetch(url + userInp)
      .then((response) => response.json())
      .then((data) => {
        document.getElementById("user-inp").value = "";
        console.log(data);
        console.log(data.drinks[0]);
        let myDrink = data.drinks[0];
        console.log(myDrink.strDrink);
        console.log(myDrink.strDrinkThumb);
        console.log(myDrink.strInstructions);
        let count = 1;
        let ingredients = [];
        for (let i in myDrink) {
          let ingredient = "";
          let measure = "";
          if (i.startsWith("strIngredient") && myDrink[i]) {
            ingredient = myDrink[i];
            if (myDrink[`strMeasure` + count]) {
              measure = myDrink[`strMeasure` + count];
            } else {
              measure = "";
            }
            count += 1;
            ingredients.push(`${measure} ${ingredient}`);
          }
        }
        console.log(ingredients);
        result.innerHTML = `
      <img src=${myDrink.strDrinkThumb}>
      <h2>${myDrink.strDrink}</h2>
      <h3>Ingredients:</h3>
      <ul class="ingredients"></ul>
      <h3>Instructions:</h3>
      <p>${myDrink.strInstructions}</p>
      `;
        let ingredientsCon = document.querySelector(".ingredients");
        ingredients.forEach((item) => {
          let listItem = document.createElement("li");
          listItem.innerText = item;
          ingredientsCon.appendChild(listItem);
        });
      })
      .catch(() => {
        result.innerHTML = `<h3 class="msg">Please enter a valid input</h3>`;
      });
  }
};
window.addEventListener("load", getInfo);
searchBtn.addEventListener("click", getInfo);

📁 Download Source Code:  https://www.codingartistweb.com

#html #css #javascript 

津田  淳

津田 淳

1683308280

如何使用 HTML、CSS 和 JavaScript 对颜色选择器进行图像处理

您想使用 JavaScript 创建图像颜色选择器吗?如果是,那么本文将帮助您完全使用 HTML CSS 和 JavaScript 创建拾色器。

我使用 html 来创建这个图像颜色选择器的基本结构。使用 sys 设计。最后,我使用 javascript 激活了这个 html 颜色选择器。

使用 JavaScript 的图像颜色选择器

Image Color Picker我们在很多网站都看到了。这是一个非常棒的元素,可以帮助您获得任何颜色的颜色代码。我们主要在图像编辑网站中看到这些项目(使用 HTML 从图像创建颜色选择器)。

使用此图像颜色选择器 JavaScript,您可以选择任何图像中的颜色并获取其颜色代码。您可以使用此项目(带有 JS 的图像颜色选择器)复制任何元素的颜色,而不仅仅是 sudu 图像的颜色。

正如您在上面看到的,为了创建此图像颜色选择器 HTML,我首先在网页上创建了一个框。在该框内是第一个上传图像的地方。上传图片后,可以在那里查看图片。然后是一个拾色器按钮。您可以通过它来选择颜色。

所选颜色的代码可以在下面的输入框中看到。不仅如此,您选择的颜色可以在下面的颜色视图框中看到。

使用 HTML、CSS 和 JavaScript 的图像颜色选择器

使用 HTML CSS 和 JavaScript 的图像颜色选择器

现在,如果您想创建此图像颜色选择器,请按照下面的教程进行操作。在这里,我分享了一步一步的教程和完整的源代码。 

如果您只想要源代码,那么您可以使用文章下方的下载按钮下载完整的源代码。

第一步:颜色选择器的基本结构

首先,我使用自己的 html 和 css 在网页上创建了一个基本结构。在网页上,我使用了background-color: #400734并且框的背景使用了白色。

<div class="wrapper">

</div>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #400734;
}
.wrapper {
  background-color: #ffffff;
  width: 90%;
  max-width: 400px;
  position: absolute;
  transform: translateX(-50%);
  left: 50%;
  top: 0.5em;
  padding: 1.5em;
  border-radius: 0.8em;
}

拾色器的基本结构

第 2 步:查看上传图片的位置

现在创建图像显示。在此图像颜色选择器中,您必须决定图像的显示位置。这是我选择的默认图像。

<div class="image-container">
  <img decoding="async" id="image" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" data-lazy-src="demo-image-3.jpg" /><noscript><img decoding="async" id="image" src="demo-image-3.jpg" /></noscript>
</div>
img {
  display: block;
  width: 90%;
  margin: auto;
}

查看上传图片的地方

第 3 步:图片上传和颜色选择器按钮

现在我们需要在这个JavaScript Image Color Picker项目中创建两个按钮。选择文件的按钮,即我要上传的图像。另一个是选择颜色。

我使用蓝色作为按钮的背景颜色,并使用它们周围的填充来定义一些大小。

<div class="btns-container">
    <input type="file" id="file" accesskey="image/*" />
    <label for="file">Open A Photo</label>
    <button id="pick-color">Pick Color</button>
</div>
.btns-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1em;
  margin: 1em 0 1.5em 0;
}
input,
label,
button {
  border: none;
  outline: none;
}
input[type="file"] {
  display: none;
}
label,
button {
  display: block;
  font-size: 1.1em;
  background-color: #025bee;
  color: #ffffff;
  text-align: center;
  padding: 0.8em 0;
  border-radius: 0.3em;
  cursor: pointer;
}

图像上传和颜色选择器按钮

第 4 步:创建输入框以查看颜色代码

现在创建两个输入框来查看颜色代码。在此输入框中可以看到颜色代码。每个输入框都有一个复制按钮,可以帮助复制该输入框中包含的信息。

这是一个小盒子,可以充当彩盒。您选择的颜色将出现在此框中。

<div id="result" class="hide">
  <div>
    <input type="text" id="hex-val-ref" />
    <button onclick="copy('hex-val-ref')">
      <i class="fa-regular fa-copy"></i>
    </button>
  </div>
  <div>
    <input type="text" id="rgb-val-ref" />
    <button onclick="copy('rgb-val-ref')">
      <i class="fa-regular fa-copy"></i>
    </button>
  </div>
  <div id="picked-color-ref"></div>
</div>
#result {
  /* display: grid; */
  grid-template-columns: 1fr 1fr;
  grid-gap: 1em;
}
#result div {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
#result input {
  background-color: transparent;
  font-size: 1em;
  padding: 0.5em;
  width: 100%;
  color: #313b4c;
  border-bottom: 0.1em solid #021637;
}
#result button {
  position: absolute;
  right: 0.6em;
  background-color: transparent;
  color: #7c8696;
}
#picked-color-ref {
  grid-column: 2;
  grid-row: 1 / 3;
  border: 0.6em solid #d9e8ff;
  border-radius: 0.5em;
}

创建输入框以查看颜色代码

我在这里用我自己的 CSS 设计了警报选项。当您通过此图像颜色选择器 html 复制颜色颜色代码时,您将在下面看到此警告消息。

#custom-alert {
  transform: scale(0);
  transition: 0.5s;
  transform-origin: center;
  background-color: #d9e8ff;
  color: #025bee;
  text-align: center;
  padding: 0.5em;
  margin-top: 1.5em;
}
.hide {
  display: none;
}
#error {
  color: #ff725a;
  text-align: center;
}

第 5 步:使用 JavaScript 激活图像颜色选择器

现在是时候用 JavaScript 实现图像颜色选择器了。这里我用了很多javascript但是很简单。如果您了解基本的 JavaScript,那么理解以下代码应该没有问题。

//Create Initial references
let pickColor = document.getElementById("pick-color");
let error = document.getElementById("error");
let fileInput = document.getElementById("file");
let image = document.getElementById("image");
let hexValRef = document.getElementById("hex-val-ref");
let rgbValRef = document.getElementById("rgb-val-ref");
let customAlert = document.getElementById("custom-alert");
let pickedColorRef = document.getElementById("picked-color-ref");
let eyeDropper;

//Function On Window Load
window.onload = () => {
  //Check if the browser supports eyedropper
  if ("EyeDropper" in window) {
    pickColor.classList.remove("hide");
    eyeDropper = new EyeDropper();
  } else {
    error.classList.remove("hide");
    error.innerText = "Your browser doesn't support Eyedropper API";
    pickColor.classList.add("hide");
    return false;
  }
};

//Eyedropper logic
const colorSelector = async () => {
  const color = await eyeDropper
    .open()
    .then((colorValue) => {
      error.classList.add("hide");
      //Get the hex color code
      let hexValue = colorValue.sRGBHex;
      //Convert Hex Value To RGB
      let rgbArr = [];
      for (let i = 1; i < hexValue.length; i += 2) {
        rgbArr.push(parseInt(hexValue[i] + hexValue[i + 1], 16));
        console.log(rgbArr);
      }
      let rgbValue = "rgb(" + rgbArr + ")";
      console.log(hexValue, rgbValue);
      result.style.display = "grid";
      hexValRef.value = hexValue;
      rgbValRef.value = rgbValue;
      pickedColorRef.style.backgroundColor = hexValue;
    })
    .catch((err) => {
      error.classList.remove("hide");
      //If user presses escape to close the eyedropper
      if (err.toString().includes("AbortError")) {
        error.innerText = "";
      } else {
        error.innerText = err;
      }
    });
};

//Button click
pickColor.addEventListener("click", colorSelector);

//Allow user to choose image of their own choice
fileInput.onchange = () => {
  result.style.display = "none";
  //The fileReader object helps to read contents of file stored on computer
  let reader = new FileReader();
  //readAsDataURL reads the content of input file
  reader.readAsDataURL(fileInput.files[0]);
  reader.onload = () => {
    //onload is triggered after file reading operation is successfully completed
    //set src attribute of image to result/input file
    image.setAttribute("src", reader.result);
  };
};

//Function to copy the color code
let copy = (textId) => {
  //Selects the text in the <input> element
  document.getElementById(textId).select();
  //Copies the selected text to clipboard
  document.execCommand("copy");
  //Display Alert
  customAlert.style.transform = "scale(1)";
  setTimeout(() => {
    customAlert.style.transform = "scale(0)";
  }, 2000);
};

使用 JavaScript 激活图像颜色选择器

希望从上面的教程中您已经学会了如何使用 HTML、CSS 和 JavaScript 创建图像颜色选择器

早些时候我和你分享了如何创建更多类型的颜色生成器,随机背景颜色生成器。评论您对这个 JavaScript Image Color Picker 项目的喜爱程度。

源代码

文章原文出处:https: //foolishdeveloper.com/

#javascript #html #css #image 

Выбор цвета изображения с использованием HTML, CSS и JavaScript

Вы хотите создать палитру цветов изображения с помощью JavaScript ? Если да, то эта статья поможет вам полностью создать палитру цветов с помощью HTML CSS и JavaScript.

Я использовал html для создания базовой структуры этой палитры цветов изображений. Разработан с использованием sys. Наконец, я активировал эту палитру цветов html с помощью javascript.

Выбор цвета изображения с помощью JavaScript

Выбор цвета изображения Мы видим на многих веб-сайтах. Это действительно отличный элемент, который поможет вам получить цветовой код любого цвета. Мы видим эти проекты (Создание палитры цветов из изображения с помощью HTML) в основном на веб-сайтах для редактирования изображений.

С помощью JavaScript для выбора цвета изображения вы можете выбрать цвет на любом изображении и получить его цветовой код. Вы можете скопировать цвет любого элемента, а не только цвет изображения sudu, с помощью этого проекта (выбор цвета изображения с помощью JS).

Как вы можете видеть выше, чтобы создать этот HTML-код для выбора цвета изображения, я сначала создал поле на веб-странице. Внутри этого поля находится первое место для загрузки изображения. После загрузки изображения изображение можно просмотреть там. Затем есть кнопка выбора цвета. По которому можно выбрать цвет.

Коды выбранных цветов можно увидеть в поле ввода ниже. Мало того, выбранный вами цвет можно увидеть в окне просмотра цвета ниже.

Выбор цвета изображения с использованием HTML, CSS и JavaScript

Выбор цвета изображения с использованием HTML CSS и JavaScript

Теперь, если вы хотите создать эту палитру цветов изображения, следуйте инструкциям ниже. Здесь я поделился пошаговым руководством и полным исходным кодом. 

Если вам нужен только исходный код, вы можете загрузить полный исходный код, используя кнопку загрузки под статьей.

Шаг 1: Базовая структура палитры цветов

Сначала я создал базовую структуру веб-страницы, используя собственные html и css. На веб-странице я использовал фоновый цвет: #400734 , а белый цвет был использован для фона коробки.

<div class="wrapper">

</div>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #400734;
}
.wrapper {
  background-color: #ffffff;
  width: 90%;
  max-width: 400px;
  position: absolute;
  transform: translateX(-50%);
  left: 50%;
  top: 0.5em;
  padding: 1.5em;
  border-radius: 0.8em;
}

Базовая структура палитры цветов

Шаг 2: Место для просмотра загруженных изображений

Теперь создайте отображение изображения. В этой палитре цветов изображения вы должны решить, где будет отображаться изображение. Вот изображение по умолчанию, которое я выбрал.

<div class="image-container">
  <img decoding="async" id="image" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" data-lazy-src="demo-image-3.jpg" /><noscript><img decoding="async" id="image" src="demo-image-3.jpg" /></noscript>
</div>
img {
  display: block;
  width: 90%;
  margin: auto;
}

Место для просмотра загруженных изображений

Шаг 3: Кнопка загрузки изображения и выбора цвета

Теперь нам нужно создать две кнопки в этом проекте JavaScript Image Color Picker . Кнопка для выбора файла, т.е. какое изображение я хочу загрузить. Другой - выбрать цвет.

Я использовал синий цвет для фона кнопок и использовал отступы вокруг них, чтобы определить размер.

<div class="btns-container">
    <input type="file" id="file" accesskey="image/*" />
    <label for="file">Open A Photo</label>
    <button id="pick-color">Pick Color</button>
</div>
.btns-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1em;
  margin: 1em 0 1.5em 0;
}
input,
label,
button {
  border: none;
  outline: none;
}
input[type="file"] {
  display: none;
}
label,
button {
  display: block;
  font-size: 1.1em;
  background-color: #025bee;
  color: #ffffff;
  text-align: center;
  padding: 0.8em 0;
  border-radius: 0.3em;
  cursor: pointer;
}

Кнопка загрузки изображения и выбора цвета

Шаг 4: Создайте поля ввода для просмотра цветовых кодов

Теперь создайте два поля ввода для просмотра цветовых кодов. Цветовые коды можно увидеть в этом поле ввода. Каждое поле ввода имеет кнопку копирования, которая поможет скопировать информацию, содержащуюся в этом поле ввода.

Вот небольшая коробка, которая будет действовать как цветная коробка. Выбранный цвет появится в этом поле.

<div id="result" class="hide">
  <div>
    <input type="text" id="hex-val-ref" />
    <button onclick="copy('hex-val-ref')">
      <i class="fa-regular fa-copy"></i>
    </button>
  </div>
  <div>
    <input type="text" id="rgb-val-ref" />
    <button onclick="copy('rgb-val-ref')">
      <i class="fa-regular fa-copy"></i>
    </button>
  </div>
  <div id="picked-color-ref"></div>
</div>
#result {
  /* display: grid; */
  grid-template-columns: 1fr 1fr;
  grid-gap: 1em;
}
#result div {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
#result input {
  background-color: transparent;
  font-size: 1em;
  padding: 0.5em;
  width: 100%;
  color: #313b4c;
  border-bottom: 0.1em solid #021637;
}
#result button {
  position: absolute;
  right: 0.6em;
  background-color: transparent;
  color: #7c8696;
}
#picked-color-ref {
  grid-column: 2;
  grid-row: 1 / 3;
  border: 0.6em solid #d9e8ff;
  border-radius: 0.5em;
}

Создайте поля ввода для просмотра цветовых кодов

Я разработал здесь опцию оповещения с помощью собственного CSS. Когда вы копируете цветовой код цвета с помощью этого html-файла Image Color Picker, вы увидите это предупреждающее сообщение ниже.

#custom-alert {
  transform: scale(0);
  transition: 0.5s;
  transform-origin: center;
  background-color: #d9e8ff;
  color: #025bee;
  text-align: center;
  padding: 0.5em;
  margin-top: 1.5em;
}
.hide {
  display: none;
}
#error {
  color: #ff725a;
  text-align: center;
}

Шаг 5. Активируйте палитру цветов изображения с помощью JavaScript

Теперь пришло время реализовать средство выбора цвета изображения с помощью JavaScript . Здесь я использовал много javascript, но это очень просто. Если вы знаете базовый JavaScript, у вас не должно возникнуть проблем с пониманием следующего кода.

//Create Initial references
let pickColor = document.getElementById("pick-color");
let error = document.getElementById("error");
let fileInput = document.getElementById("file");
let image = document.getElementById("image");
let hexValRef = document.getElementById("hex-val-ref");
let rgbValRef = document.getElementById("rgb-val-ref");
let customAlert = document.getElementById("custom-alert");
let pickedColorRef = document.getElementById("picked-color-ref");
let eyeDropper;

//Function On Window Load
window.onload = () => {
  //Check if the browser supports eyedropper
  if ("EyeDropper" in window) {
    pickColor.classList.remove("hide");
    eyeDropper = new EyeDropper();
  } else {
    error.classList.remove("hide");
    error.innerText = "Your browser doesn't support Eyedropper API";
    pickColor.classList.add("hide");
    return false;
  }
};

//Eyedropper logic
const colorSelector = async () => {
  const color = await eyeDropper
    .open()
    .then((colorValue) => {
      error.classList.add("hide");
      //Get the hex color code
      let hexValue = colorValue.sRGBHex;
      //Convert Hex Value To RGB
      let rgbArr = [];
      for (let i = 1; i < hexValue.length; i += 2) {
        rgbArr.push(parseInt(hexValue[i] + hexValue[i + 1], 16));
        console.log(rgbArr);
      }
      let rgbValue = "rgb(" + rgbArr + ")";
      console.log(hexValue, rgbValue);
      result.style.display = "grid";
      hexValRef.value = hexValue;
      rgbValRef.value = rgbValue;
      pickedColorRef.style.backgroundColor = hexValue;
    })
    .catch((err) => {
      error.classList.remove("hide");
      //If user presses escape to close the eyedropper
      if (err.toString().includes("AbortError")) {
        error.innerText = "";
      } else {
        error.innerText = err;
      }
    });
};

//Button click
pickColor.addEventListener("click", colorSelector);

//Allow user to choose image of their own choice
fileInput.onchange = () => {
  result.style.display = "none";
  //The fileReader object helps to read contents of file stored on computer
  let reader = new FileReader();
  //readAsDataURL reads the content of input file
  reader.readAsDataURL(fileInput.files[0]);
  reader.onload = () => {
    //onload is triggered after file reading operation is successfully completed
    //set src attribute of image to result/input file
    image.setAttribute("src", reader.result);
  };
};

//Function to copy the color code
let copy = (textId) => {
  //Selects the text in the <input> element
  document.getElementById(textId).select();
  //Copies the selected text to clipboard
  document.execCommand("copy");
  //Display Alert
  customAlert.style.transform = "scale(1)";
  setTimeout(() => {
    customAlert.style.transform = "scale(0)";
  }, 2000);
};

Активируйте палитру цветов изображения с помощью JavaScript

Надеемся, что из приведенного выше руководства вы узнали, как создать палитру цветов изображения с помощью HTML, CSS и JavaScript .

Ранее я поделился с вами тем, как создать больше типов генераторов цвета , генераторов случайного цвета фона . Напишите, как вам нравится этот проект JavaScript Image Color Picker.

Исходный код

Оригинальный источник статьи: https://foolishdeveloper.com/

#javascript #html #css #image 

How to Image Color Picker using HTML, CSS and JavaScript

Do you want to create Image Color Picker using JavaScript? If yes then this article will help you completely to create Color Picker using HTML CSS and JavaScript.

I used html to create the basic structure of this Image Color Picker. Designed using sys. Finally I activated this html color picker using javascript.

Image Color Picker With JavaScript

Image Color Picker We see in many websites. This is a really great element that will help you get the color code of any color. We see these projects(Create Color Picker From Image Using HTML) mostly in image editing websites.

With this Image Color Picker JavaScript you can select the color in any image and get its color code. You can copy the color of any element, not just the color of the sudu image, with this project(image color picker with JS).

As you can see above to create this Image Color Picker HTML I first created a box on the webpage. Inside that box is the first place to upload an image. After uploading the image, the image can be viewed there. Then there is a Color Picker button. By which you can select the color.

The codes of the selected colors can be seen in an input box below. Not only that, the color you have selected can be seen in the color view box below.

Image Color Picker using HTML, CSS and JavaScript

Image Color Picker Using HTML CSS & JavaScript

Now if you want to create this Image Color Picker then follow the tutorial below. Here I have shared step by step tutorial and complete source code. 

If you just want the source code then you can download the complete source code using the download button below the article.

Step 1: Basic Structure Of Color Picker

First I created a basic structure on the web page using my own html and css. On the webpage I used background-color: #400734and white color was used for the background of the box.

<div class="wrapper">

</div>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #400734;
}
.wrapper {
  background-color: #ffffff;
  width: 90%;
  max-width: 400px;
  position: absolute;
  transform: translateX(-50%);
  left: 50%;
  top: 0.5em;
  padding: 1.5em;
  border-radius: 0.8em;
}

Basic Structure Of Color Picker

Step 2: Place To View Uploaded Images

Now create an image display. In this Image Color Picker you have to decide where the image will be displayed. Here is a default image I have selected.

<div class="image-container">
  <img decoding="async" id="image" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" data-lazy-src="demo-image-3.jpg" /><noscript><img decoding="async" id="image" src="demo-image-3.jpg" /></noscript>
</div>
img {
  display: block;
  width: 90%;
  margin: auto;
}

Place To View Uploaded Images

Step 3: Image Upload And Color Picker Button

Now we need to create two buttons in this JavaScript Image Color Picker project. A button to select file ie which image i want to upload. Another is to select the color.

I used blue for the background color of the buttons and used padding around them to define some size as well.

<div class="btns-container">
    <input type="file" id="file" accesskey="image/*" />
    <label for="file">Open A Photo</label>
    <button id="pick-color">Pick Color</button>
</div>
.btns-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1em;
  margin: 1em 0 1.5em 0;
}
input,
label,
button {
  border: none;
  outline: none;
}
input[type="file"] {
  display: none;
}
label,
button {
  display: block;
  font-size: 1.1em;
  background-color: #025bee;
  color: #ffffff;
  text-align: center;
  padding: 0.8em 0;
  border-radius: 0.3em;
  cursor: pointer;
}

Image Upload And Color Picker Button

Step 4: Create Input Boxes To View Color Codes

Now create two input boxes to view the color codes. Color codes can be seen in this input box. Each input box has a copy button which will help to copy the information contained in that input box.

Here is a small box that will act as a color box. The color you select will appear in this box.

<div id="result" class="hide">
  <div>
    <input type="text" id="hex-val-ref" />
    <button onclick="copy('hex-val-ref')">
      <i class="fa-regular fa-copy"></i>
    </button>
  </div>
  <div>
    <input type="text" id="rgb-val-ref" />
    <button onclick="copy('rgb-val-ref')">
      <i class="fa-regular fa-copy"></i>
    </button>
  </div>
  <div id="picked-color-ref"></div>
</div>
#result {
  /* display: grid; */
  grid-template-columns: 1fr 1fr;
  grid-gap: 1em;
}
#result div {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
#result input {
  background-color: transparent;
  font-size: 1em;
  padding: 0.5em;
  width: 100%;
  color: #313b4c;
  border-bottom: 0.1em solid #021637;
}
#result button {
  position: absolute;
  right: 0.6em;
  background-color: transparent;
  color: #7c8696;
}
#picked-color-ref {
  grid-column: 2;
  grid-row: 1 / 3;
  border: 0.6em solid #d9e8ff;
  border-radius: 0.5em;
}

Create Input Boxes To View Color Codes

I designed the alert option here with my own CSS. When you copy the color color code by this Image Color Picker html you will see this alert message below.

#custom-alert {
  transform: scale(0);
  transition: 0.5s;
  transform-origin: center;
  background-color: #d9e8ff;
  color: #025bee;
  text-align: center;
  padding: 0.5em;
  margin-top: 1.5em;
}
.hide {
  display: none;
}
#error {
  color: #ff725a;
  text-align: center;
}

Step 5: Activate The Image Color Picker With JavaScript

Now it’s time to implement the Image Color Picker with JavaScript. Here I have used a lot of javascript but it is very simple. If you know basic JavaScript then you should have no problem understanding the following code.

//Create Initial references
let pickColor = document.getElementById("pick-color");
let error = document.getElementById("error");
let fileInput = document.getElementById("file");
let image = document.getElementById("image");
let hexValRef = document.getElementById("hex-val-ref");
let rgbValRef = document.getElementById("rgb-val-ref");
let customAlert = document.getElementById("custom-alert");
let pickedColorRef = document.getElementById("picked-color-ref");
let eyeDropper;

//Function On Window Load
window.onload = () => {
  //Check if the browser supports eyedropper
  if ("EyeDropper" in window) {
    pickColor.classList.remove("hide");
    eyeDropper = new EyeDropper();
  } else {
    error.classList.remove("hide");
    error.innerText = "Your browser doesn't support Eyedropper API";
    pickColor.classList.add("hide");
    return false;
  }
};

//Eyedropper logic
const colorSelector = async () => {
  const color = await eyeDropper
    .open()
    .then((colorValue) => {
      error.classList.add("hide");
      //Get the hex color code
      let hexValue = colorValue.sRGBHex;
      //Convert Hex Value To RGB
      let rgbArr = [];
      for (let i = 1; i < hexValue.length; i += 2) {
        rgbArr.push(parseInt(hexValue[i] + hexValue[i + 1], 16));
        console.log(rgbArr);
      }
      let rgbValue = "rgb(" + rgbArr + ")";
      console.log(hexValue, rgbValue);
      result.style.display = "grid";
      hexValRef.value = hexValue;
      rgbValRef.value = rgbValue;
      pickedColorRef.style.backgroundColor = hexValue;
    })
    .catch((err) => {
      error.classList.remove("hide");
      //If user presses escape to close the eyedropper
      if (err.toString().includes("AbortError")) {
        error.innerText = "";
      } else {
        error.innerText = err;
      }
    });
};

//Button click
pickColor.addEventListener("click", colorSelector);

//Allow user to choose image of their own choice
fileInput.onchange = () => {
  result.style.display = "none";
  //The fileReader object helps to read contents of file stored on computer
  let reader = new FileReader();
  //readAsDataURL reads the content of input file
  reader.readAsDataURL(fileInput.files[0]);
  reader.onload = () => {
    //onload is triggered after file reading operation is successfully completed
    //set src attribute of image to result/input file
    image.setAttribute("src", reader.result);
  };
};

//Function to copy the color code
let copy = (textId) => {
  //Selects the text in the <input> element
  document.getElementById(textId).select();
  //Copies the selected text to clipboard
  document.execCommand("copy");
  //Display Alert
  customAlert.style.transform = "scale(1)";
  setTimeout(() => {
    customAlert.style.transform = "scale(0)";
  }, 2000);
};

Activate The Image Color Picker With JavaScript

Hopefully from the above tutorial you have learned how to create an Image Color Picker using HTML, CSS and JavaScript.

Earlier I shared with you how to create more types of color generators, random background color generators. Comment how you like this JavaScript Image Color Picker project.

Source Code

Original article source at: https://foolishdeveloper.com/

#javascript #html #css #image 

A different way to visualize classification results

I love good data visualizations. Back in the days when I did my PhD in particle physics, I was stunned by the histograms my colleagues built and how much information was accumulated in one single plot.


Information in Plots

It is really challenging to improve existing visualization methods or to transport methods from other research fields. You have to think about the dimensions in your plot and the ways to add more of them. A good example is the path from a boxplot to a violinplot to a swarmplot. It is a continuous process of adding dimensions and thus information.

The possibilities of adding information or dimensions to a plot are almost endless. Categories can be added with different marker shapes, color maps like in a heat map can serve as another dimension and the size of a marker can give insight to further parameters.

Plots of Classifier Performance

When it comes to machine learning, there are many ways to plot the performance of a classifier. There is an overwhelming amount of metrics to compare different estimators like accuracy, precision, recall or the helpful MMC.

All of the common classification metrics are calculated from true positive, true negative, _false positive _and _false negative _incidents. The most popular plots are definitely ROC curve, PRC, CAP curve and the confusion matrix.

I won’t get into detail of the three curves, but there are many different ways to handle the confusion matrix, like adding a heat map.

A seaborn heatmap of a confusion matrix.

#matplotlib #machine-learning #classification #python #plot